note 81493 added to language.oop5.magic

From: Date: Sat, 01 Mar 2008 02:31:12 +0000
Subject: note 81493 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-136626@lists.php.net to get a copy of this message
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); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 24.22.133.183 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/81493 Del: integrated -- https://master.php.net/note/delete/81493/integrated Del: useless -- https://master.php.net/note/delete/81493/useless Del: bad code -- https://master.php.net/note/delete/81493/bad+code Del: spam -- https://master.php.net/note/delete/81493/spam Del: non-english -- https://master.php.net/note/delete/81493/non-english Del: in docs -- https://master.php.net/note/delete/81493/in+docs Del: other reasons-- https://master.php.net/note/delete/81493 Reject -- https://master.php.net/note/reject/81493 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#136626) next »