note 81493 deleted from language.oop5.magic by nlopess
| From: | nlopess@php.net | Date: | Sat, 01 Mar 2008 12:17:32 +0000 |
| Subject: | note 81493 deleted from language.oop5.magic by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-136635@lists.php.net to get a copy of this message | ||
Note Submitter: dave
----
With PHP 5.2.3, If you want to serialize an object that is part of an object hierarchy and you want
to selectively serialize members (public, private, and protected) by manually specifying the array
of members, there are a few simple rules for naming members that you must follow:
1. public members should be named using just their member name, like so:
<?php
class Foo {
public $bar;
public function __sleep() {
return array("bar");
}
}
?>
2. protected members should be named using "\0" . "*" . "\0" . member
name, like so:
<?php
class Foo {
protected $bar;
public function __sleep() {
return array("\0*\0bar");
}
}
?>
3. private members should be named using "\0" . class name . "\0" . member name,
like so:
<?php
class Foo {
private $bar;
public function __sleep() {
return array("\0Foo\0bar");
}
}
?>
So with this information let us serialize a class hierarchy correctly:
<?php
class Base {
private $foo = "foo_value";
protected $bar = "bar_value";
public function __sleep() {
return array("\0Base\0foo", "\0*\0bar");
}
}
class Derived extends Base {
public $baz = "baz_value";
private $boo = "boo_value";
public function __sleep() {
// we have to merge our members with our parent's
return array_merge(array("baz", "\0Derived\0boo"), parent::__sleep());
}
}
class Leaf extends Derived {
private $qux = "qux_value";
protected $zaz = "zaz_value";
public $blah = "blah_value";
public function __sleep() {
// again, merge our members with our parent's
return array_merge(array("\0Leaf\0qux", "\0*\0zaz", "blah"),
parent::__sleep());
}
}
// test it
$test = new Leaf();
$s = serialize($test);
$test2 = unserialize($s);
echo $s;
print_r($test);
print_r($test2);
?>