note 99668 deleted from language.references by googleguy

From: Date: Wed, 01 Aug 2012 11:00:57 +0000
Subject: note 99668 deleted from language.references by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189559@lists.php.net to get a copy of this message
Note Submitter: dev dot php at linke-t dot net ---- I thought Yeah pointer likly behavior... but i watched serilized objects and what i did see? referenced Objects are outputed like the object self. Here is a simple code, it shows that the references are sweet but in some case (storing objects to $_SESSION or Database) unuseable: <?php class foo{ private static $id_c = 0; public $ref; public $id; public function foo(){ $this->id=self::$id_c++; } } $a = new foo(); $b = new foo(); $a->ref = &$b; print_r($a); echo "<br/>"; print_r($b); echo "<br/><br/>"; $a->ref->id++; echo "increment \$a->ref->id++;<br/><br/>"; print_r($a); echo "<br/>"; print_r($b); echo "<br/><br/>"; echo "\$a2=unserialize(serialize(\$a));<br/><br/>"; $a2=unserialize(serialize($a)); print_r($a2); echo "<br/>"; print_r($b); echo "<br/><br/>"; $a2->ref->id++; echo "increment \$a2->ref->id++;<br/><br/>"; print_r($a2); echo "<br/>"; print_r($b); echo "<br/>"; ?> Output on PHP 5.3.3: foo Object ( [ref] => foo Object ( [ref] => [id] => 1 ) [id] => 0 ) foo Object ( [ref] => [id] => 1 ) increment $a->ref->id++; foo Object ( [ref] => foo Object ( [ref] => [id] => 2 ) [id] => 0 ) foo Object ( [ref] => [id] => 2 ) $a2=unserialize(serialize($a)); foo Object ( [ref] => foo Object ( [ref] => [id] => 2 ) [id] => 0 ) foo Object ( [ref] => [id] => 2 ) increment $a2->ref->id++; foo Object ( [ref] => foo Object ( [ref] => [id] => 3 ) [id] => 0 ) foo Object ( [ref] => [id] => 2 ) after unserialize $a2->ref isn't any more a reference. To save items for the next request, you must avoid references and save all objects of a class in an array. To get a PHP-reference you could write a function like: <?php function get_obj_by_ref($ref){ global $_array_where_objects_of_class_foo_are_stored; $r = &$_array_where_objects_of_class_foo_are_stored[$ref]; return $r; } ?> I am unhappy about this behavior of PHP. I does not watch like a feature ... ;)

« previous php.notes (#189559) next »