note 99668 added to language.references

From: Date: Mon, 30 Aug 2010 09:01:16 +0000
Subject: note 99668 added to language.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-172155@lists.php.net to get a copy of this message
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 ... ;) ---- Server IP: 69.147.83.197 Probable Submitter: 91.39.87.88 ---- Manual Page -- http://www.php.net/manual/en/language.references.php Edit -- https://master.php.net/note/edit/99668 Del: integrated -- https://master.php.net/note/delete/99668/integrated Del: useless -- https://master.php.net/note/delete/99668/useless Del: bad code -- https://master.php.net/note/delete/99668/bad+code Del: spam -- https://master.php.net/note/delete/99668/spam Del: non-english -- https://master.php.net/note/delete/99668/non-english Del: in docs -- https://master.php.net/note/delete/99668/in+docs Del: other reasons-- https://master.php.net/note/delete/99668 Reject -- https://master.php.net/note/reject/99668 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172155) next »