• 0

[PHP] Cast Object to specific class


Question

Hey guys, I have an Array of TimeSpan objects and I'm storing them in Sessions (bad idea?), and then when I read them out again they're just normal objects. Is there a way to cast them back? Or am I best off trying to manually copy the data into a new object?

Cheers!

Link to comment
https://www.neowin.net/forum/topic/678760-php-cast-object-to-specific-class/
Share on other sites

9 answers to this question

Recommended Posts

  • 0
  zer0day said:
Try something like:

$timespan = (TimeSpan) $array[$index];

Sorry, I had a work around to this problem, but apparently not. :p

$Schedules = $_SESSION["SingleSchedules"];
foreach($Schedules as $Schedule)
{
	$NewSchedule = (Schedule) $Schedule;
	$Schedule->Enabled = 1;
	$Schedule->Save(true);
}

Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\schedule\create.php on line 9 (the cast line)

:(

  • 0

Serialise the objects before you store them and un-serialise them when you retrieve them

http://uk.php.net/manual/en/function.serialize.php

As for storing them in sessions, why not just store the data on the server and just set the ID in a session/cookie? Less susceptible to maliciousness that way.

  • 0
  M2Ys4U said:
Serialise the objects before you store them and un-serialise them when you retrieve them

http://uk.php.net/manual/en/function.serialize.php

As for storing them in sessions, why not just store the data on the server and just set the ID in a session/cookie? Less susceptible to maliciousness that way.

Actually, it appears to be working now with calling the functions directly. *confused* Perhaps I was doing something stupid last time.

I thought all that was stored in a cookie was a Session ID? I'm storing a User Object in Sessions as well.. is it safe?

If not how would you recommend storing the data? I spose an example of what I'm doing is an Order System, where you have an Order (or cart) and Products that belong to that cart. At any time you can just leave the page and the cart+contents will be removed. I was originally doing it directly into the database, but then you have to schedule deletion of those unwanted carts and it just didn't feel very professional. :(

  • 0
  M2Ys4U said:
Erm, true. I was thinking more along the lines of cookies rather than sessions.

Ok cool. :p I only just remembered that you could access cookies using $_COOKIE, so I thought everyone was talking about $_SESSION being unsecure. :p

  • 0
class TimeSpan 
{
public function __sleep() {
// actions to perform when serialized (e.g. close database connection)
}

public function __wakeup() {
// actions to perform when unserialized (e.g. reopen database connection)
}
}

$_SESSION['object'] = serialize(new TimeSpan);
$object = unserialize($_SESSION['object']);

  • 0
  On 13/10/2008 at 03:54, Pc_Madness said:

Actually, it appears to be working now with calling the functions directly. *confused* Perhaps I was doing something stupid last time.

I thought all that was stored in a cookie was a Session ID? I'm storing a User Object in Sessions as well.. is it safe?

If not how would you recommend storing the data? I spose an example of what I'm doing is an Order System, where you have an Order (or cart) and Products that belong to that cart. At any time you can just leave the page and the cart+contents will be removed. I was originally doing it directly into the database, but then you have to schedule deletion of those unwanted carts and it just didn't feel very professional. :(

Session data should be safe enough. Session hijacking happens if a cookie on a legitimate visitor's machine is captured and reused by an attacker while their session is still active. Not muc h you can do about this on the server side, I think.

HTTP is a stateless protocol. Leaving a WEBSITE - good enough reason to delete session data, but impossible to detect. Best case scenario - a session times out after no activity for some time period

Deleting expired session or cache data periodically is how most big applications do things. Defer costly operations if you can. Realtime purging of records/data just hurts performance, unless you struggle for session storage space, etc.. Better only do a mass cleanup when the site is not busy, etc.. Depending on indexes(if you're using a database for sesions) it may be VERY time/cpu/io consuming to delete records..

PHP's default session storage media is files, I think. can get slow with massive numbers of files, some filesystems experience delays if too many files in a folder. It's not too hard to make that session files folder a ramdisk one for more speed. Or, if you have enough tin, use a memcached server/cluster for sessions - for more scalability ;-)

In the case where you are concerned about session storage efficiency - only store visitor specific data in sessions, and everything else that is reusable - in APC/Memcached/database so your visitors keep using the very same physical cached data ;-)

Just my $.02

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I have the Pixel 9 Pro XL...Unless this thing is "leaps and bounds" faster than the 9, I'll pass. And by leaps and bounds, I don't mean on benchmarks. "Real world" faster. Most people don't even come close to topping out the performance of their phones. Tensor G5 is Google's most powerful chip to date, boasting a staggering 36 percent performance leap over G4.
    • MIT's stunning 'bubble wrap' device squeezes water out from thin air even in deserts by Sayan Sen Image by Matteo Roman via Pexels Massachusetts Institute of Technology (MIT) engineers have built a new kind of device that can pull clean drinking water straight out of the air—no electricity needed. It’s designed for areas where water is scarce and traditional sources like rivers or lakes aren’t reliable. Right now, more than 2.2 billion people globally don’t have access to safe drinking water. In the United States alone, 46 million face water insecurity, with either no running water or water that’s not safe to drink. This new device, called an Atmospheric Water Harvesting Window (AWHW), uses a unique hydrogel panel that looks like black bubble wrap. These dome-shaped bubbles soak up water vapor from the air, especially at night when humidity is higher. During the day, sunlight makes the vapor inside evaporate. That vapor then condenses on a glass surface and drips down through a tube, turning into drinkable water. The AWHW doesn’t rely on power sources like batteries or solar panels. It’s completely passive, meaning it works on its own. The team tested a meter-sized panel in Death Valley, California, one of the driest places in North America, and got between 57.0 and 161.5 milliliters of water per day even with humidity as low as 21 percent. That’s more than what other similar passive devices have managed. “We have built a meter-scale device that we hope to deploy in resource-limited regions, where even a solar cell is not very accessible,” said Xuanhe Zhao, a professor at MIT. “It’s a test of feasibility in scaling up this water harvesting technology. Now people can build it even larger, or make it into parallel panels, to supply drinking water to people and achieve real impact.” Another cool part of the design is how they kept the water safe to drink. Usually, these kinds of hydrogels use salts like lithium chloride to absorb more vapor but that can lead to salt leaking into the water, which isn’t ideal. To solve this, MIT’s team mixed in glycerol, a compound that helps keep salt locked inside the gel. In testing, the lithium ion concentration in the harvested water stayed below 0.06 ppm (parts per million), which is way below the safe limit. The hydrogel domes also give the material more surface area, letting it collect more vapor. The outer glass panel is coated with a special polymer film that helps cool the glass, making it easier for vapor to condense. “This is just a proof-of-concept design, and there are a lot of things we can optimize,” said lead author Chang Liu, now a professor at the National University of Singapore. “For instance, we could have a multipanel design. And we’re working on a next generation of the material to further improve its intrinsic properties.” Published in Nature Water, the study says the AWHW could last at least a year and shows promise for making safe, sustainable water in places with harsh climates. The researchers believe an array of vertical panels could one day supply water to individual households, especially in remote or off-grid locations. Source: MIT News, Nature This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • Clear Linux is open source, indeed, so its source code is available for anyone. They're just shutting down its support from them, they're not forbidding anyone else from taking over.
    • Linux Mint is also my favorite distro, but I fear what will happen with it if Clem were to disappear tomorrow, to be honest.
    • Yeah, I totally get your point, which is possible it could happen. I just hope there is a few people around him who are similar to where if they took over things would run pretty much the same. if not, then yeah, it could start to decline rapidly etc. but I figure something that's been around for a longer period of time with a decent backing, and probably more users than most Linux distro's (which I would 'imagine' Mint is one of the more used Linux desktop distro's by volume of people who use it), is less likely to just disappear. but like you said, nothing is guaranteed. but I do think you are probably right in that Clem is probably the core of what keeps Mint, Mint. I like how it tends to stay pretty much the same with some slight tweaks here and there (but is largely the same) instead of that crap some people go for with change for the sake of change trying to create a overly fancy interface and other unnecessary stuff etc. I also feel Mint keeps a nice balance of things out-of-the-box where it's not too bloated, nor too striped down. p.s. but I see Mint as a better Ubuntu basically. but I get your point like if it was more of a really serious choice of needing a 'safe bet' to use long term, then yeah something like official Ubuntu would be one of the better choices for sure given what you said with it being backed by an actual company which makes it a safer bet than Mint which is smaller and 'could' potentially be more fragile.
  • Recent Achievements

    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
    • Dedicated
      MacDaddyAz earned a badge
      Dedicated
    • Explorer
      cekicen went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      209
    3. 3
      Michael Scrip
      202
    4. 4
      Xenon
      144
    5. 5
      +FloatingFatMan
      121
  • Tell a friend

    Love Neowin? Tell a friend!