note 78825 deleted from language.oop5.basic by felipe

From: Date: Mon, 24 Mar 2008 22:13:26 +0000
Subject: note 78825 deleted from language.oop5.basic by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137476@lists.php.net to get a copy of this message
Note Submitter: patrickr at cyberflowsolutions dot com ---- Running on PHP v5.2.3 / Zend v2.2.0... When creating a new variable and if you use the same scalar name, the 'pointer' ID doesn't update. <?php class testObj { public $val; function __construct($var) { $this->val = $var; } } class testList { private $list; function create(&$obj) { $this->list[] =& $obj; } function get($id) { return $this->list[$id]; } function display() { var_dump($this->list); } } $theList = new testList(); $obj = new testObj("this value is set"); $theList->create($obj); $obj = new testObj("but what about this one?"); $theList->create($obj); echo "[Obj1]) " . $theList->get(0)->val . "\n"; echo "[Obj2]) " . $theList->get(1)->val . "\n"; $var = $theList->get(0); echo "[\$var]) " . $var->val . "\n"; echo "[Obj1]) " . $theList->get(0)->val . "\n"; echo "[Obj2]) " . $theList->get(1)->val . "\n"; $var->val = "we are changing the value"; echo "[\$var] " . $var->val . "\n"; echo "[Obj1] " . $theList->get(0)->val . "\n"; echo "[Obj2]) " . $theList->get(1)->val . "\n"; $theList->display(); // OUTPUT /* [Obj1]) but what about this one? [Obj2]) but what about this one? [$var]) but what about this one? [Obj1]) but what about this one? [Obj2]) but what about this one? [$var] we are changing the value [Obj1] we are changing the value [Obj2]) we are changing the value array(2) { [0]=> &object(testObj)#3 (1) { ["val"]=> string(25) "we are changing the value" } [1]=> &object(testObj)#3 (1) { ["val"]=> string(25) "we are changing the value" } } */ ?> Therefore, using an array to preload where new() is referecing the data from is recommended when creating arrays of references from a loop. <?php $obj = array(); $obj[0] = new testObj("this value is set"); $theList->create($obj[0]); $obj[1] = new testObj("but what about this one?"); $theList->create($obj[1]); // OUTPUT /* [Obj1]) this value is set [Obj2]) but what about this one? [$var]) this value is set [Obj1]) this value is set [Obj2]) but what about this one? [$var] we are changing the value [Obj1] we are changing the value [Obj2]) but what about this one? array(2) { [0]=> &object(testObj)#2 (1) { ["val"]=> string(25) "we are changing the value" } [1]=> &object(testObj)#3 (1) { ["val"]=> string(24) "but what about this one?" } } */ ?>

« previous php.notes (#137476) next »