note 83556 added to language.oop5.magic
| From: | Anonymous at osu1 dot php dot net | Date: | Sat, 31 May 2008 23:24:37 +0000 |
| Subject: | note 83556 added to language.oop5.magic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140035@lists.php.net to get a copy of this message | ||
Serializing objects is problematic with references. This is solved redefining the __sleep() magic
method. This is also problematic when parent class has private variables since the parent object is
not accessible nor its private variables from within the child object.
I found a solution that seems working for classes that implements this __sleep() method, and for its
subclasses. Without more work in subclasses. The inheritance system does the trick.
Recursively __sleep() call parent' __sleep() and return the whole array of variables of the
object instance to be serialized.
<?php
class foo {
}
class a {
private $var1;
function __construct(foo &$obj = NULL) {
$this->var1 = &$obj;
}
/** Return its variables array, if its parent exists and the __sleep method is accessible, call it
and push the result into the array and return the whole thing. */
public function __sleep() {
$a = array_keys(get_object_vars(&$this));
if (method_exists(parent, '__sleep')) {
$p = parent::__sleep();
array_push($a, $p);
};
return $a;
}
}
class b extends a {
function __construct(foo &$obj = NULL) {
parent::__construct($obj);
}
}
session_start();
$myfoo = &new foo();
$myb = &new b($myfoo);
$myb = unserialize(serialize(&$myb));
?>
This should work, I haven't tested deeper.
----
Server IP: 212.124.37.9
Probable Submitter: 82.225.84.206
----
Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php
Edit -- https://master.php.net/note/edit/83556
Del: integrated -- https://master.php.net/note/delete/83556/integrated
Del: useless -- https://master.php.net/note/delete/83556/useless
Del: bad code -- https://master.php.net/note/delete/83556/bad+code
Del: spam -- https://master.php.net/note/delete/83556/spam
Del: non-english -- https://master.php.net/note/delete/83556/non-english
Del: in docs -- https://master.php.net/note/delete/83556/in+docs
Del: other reasons-- https://master.php.net/note/delete/83556
Reject -- https://master.php.net/note/reject/83556
Search -- https://master.php.net/manage/user-notes.php