Re: Serializing objects and storing them is sessions [fixed]
| From: | Kelly Hallman | Date: | Sat, 10 Apr 2004 00:51:20 +0000 |
| Subject: | Re: Serializing objects and storing them is sessions [fixed] | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-183042@lists.php.net to get a copy of this message | ||
Apr 9 at 2:49pm, Jason Giangrande wrote:
> Kelly Hallman wrote:
> > Try it without serializing, it works.
>
> After retesting, it seems you are correct. I guess the same bad
> __sleep() code that was causing the object not to unserialize at all was
> also preventing automatic serialization.
For some reason, if I include a __sleep() method in an object, PHP
segfaults on me...so I couldn't tell you anything about that :) Argh!
> However; it does not seem to harm anything if serialize() and
> unserialize() are called manually on an object. It's just extra code
> that doesn't do anything, and therefore, can be removed.
In my testing, I tried to create an array with a value that was an object.
I serialized that, and the object was not serialized and that key did not
appear in the returned serialized representation of that array.
I don't know the default session handler's internals, but if you look at a
session file that it creates, it seems to serialize the $_SESSION array.
If any of the values are objects, they appear to be serialized as well.
Given the above facts, my guess is that the handler actually goes through
and serializes any session variables that are objects (or perhaps any
values !is_scalar()), then serializes the entire $_SESSION array.
If that is the case, my original claim that a session variable that was
serialized would then be serialized again is probably untrue. The reason
being that the serialized session variable would be a scalar value and the
asession handler would not serialize it again.
So you're correct, it's the same difference. The only downside I can see
to serializing it yourself is that you've got to always unserialize it
before you can do anything with it. Then, you'd also need to reserialize
it and store the result back into that session variable.
If you just let the session handler do the serialization then you can use
that object directly and any changes would not require reassignment.
$User =& $_SESSION['User'];
$User->loggedin = true;
versus
$User = unserialize($_SESSION['User']);
$User->loggedin = true;
$_SESSION['User'] = serialize($User);
Of course, the first example could also be written as:
$_SESSION['User']->loggedin = true;
I always assumed that serialize would just serialize objects that were
within an array, and that the session handler was merely doing something
like serialize($_SESSION); So I learned something about serialize() and
the session handler's behavior in regards to how it deals with objects.
--
Kelly Hallman