note 55798 deleted from language.oop.serialization by danbrown

From: Date: Sat, 07 Nov 2009 19:12:51 +0000
Subject: note 55798 deleted from language.oop.serialization by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162601@lists.php.net to get a copy of this message
Note Submitter: fluw at gmx dot net ---- never serialize an object, if it contains references to itself. Just create the object in an array, or make a reference of this object in an array before calling serialize() and serialize the array instead of the object. print_r is fine to validate a reference: The reference will be serialized in a right way, if print_r returns a *recursive* on right place (look carefully). Just have a look on this small example: <? class foo { var $bar; function addBar() { $this->bar = new bar(&$this); } } class bar { var $parentFoo; function bar(&$partentBean) { $this->parentFoo =& $partentBean; } } $foo = new foo(); $foo->addBar(); $fooArray = array(&$foo); echo "<pre>"; print_r($foo); echo serialize($foo); echo "</pre>"; echo "<pre>"; print_r($fooArray); echo serialize($fooArray); echo "</pre>"; ?> OutPut: foo Object ( [bar] => bar Object ( [parentFoo] => foo Object ( [bar] => *RECURSION* ) ) ) O:3:"foo":1:{s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";O:3:"foo":1: {s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";R:3;}}}} //sorry for linebreak Array ( [0] => foo Object ( [bar] => bar Object ( [parentFoo] => *RECURSION* ) ) ) a:1:{i:0;O:3:"foo":1:{s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";R:2;}}} if you serialize the object, the the refernce becomes a copy an first the reference inside the copy is a real reference, (but just only to the copy, for sure :).

« previous php.notes (#162601) next »