|
-
Mar 5th, 2006, 01:31 PM
#1
[RESOLVED] object serialisation
When an object is serialised using the serialize() function, does that include objects stored by reference as member variables in the original object? If not, will they be serialised if stored as explicit copies? Or is there no way to serialise the whole thing at once?
Cheers
- P
-
Mar 5th, 2006, 01:49 PM
#2
Re: object serialisation
Yes and yes. PHP does howeverkeep track of specific object instances so if you have recursive object refernece, PHP will not go on an serialise forever. Also, if you serailise several objects which contain a reference to a common object (i.e. an owner), then the common object will only be serialised and sotred once.
There is a solution if you do not want to preserve the objects entire state. These are the __sleep() and __wakeup() magic functions. Use __sleep() to return an array of properties to serialise and __wakeup() to restablish the vlaues of any other properties when unserialising the object.
PHP Code:
class Serializable
{
var $db;
var $property1;
var $property2;
function Serializable($p1, $p2)
{
$this->property1 = $p1;
$this->proeprty2 = $p2;
$this->db = new MySqlDB('blah', 'blah', 'blah');
}
function __sleep()
{
return array('property1', 'property2');
}
function __wake()
{
$this->db = new MySqlDB('blah', 'blah', 'blah');
}
}
Obviously, in PHP 5, you'll need to declare these functions a public. However,the properties do not need to be public. I also found in PHP 5, that if the class you are serialising is a descendant, only the __sleep() and __wakeup() functions for the descendant class are called. This means that if you want to preserve any properties in the parent class, you will have to ensure its properties are either declared public or protected and add them to the array in the __sleep function.
-
Mar 5th, 2006, 01:58 PM
#3
Re: object serialisation
Sweet. Thanks 
Another related question. If I store an object reference in a session variable, would that preserve its referenced objects? I wasn't sure which is why I was looking into serialising it instead.
-
Mar 5th, 2006, 02:03 PM
#4
Re: object serialisation
If you look at the session files gnereated, you'll see that the variables stored in $_SESSION are serialised, hence, the __sleep() and __wakeup() functions are called and all that I said above applies
-
Mar 5th, 2006, 02:16 PM
#5
Re: object serialisation
Thanks! 
Will spread happiness and joy in return.
Edit: In due course, as is deemed necessary.
-
Mar 5th, 2006, 03:08 PM
#6
Re: object serialisation
Feel free to rate me negatively if you find serialisation offensive .
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|