note 39776 added to language.references.unset

From: Date: Tue, 10 Feb 2004 13:27:33 +0000
Subject: note 39776 added to language.references.unset
Groups: php.notes 
Request: Send a blank email to php-notes+get-64948@lists.php.net to get a copy of this message
now, i really consider this to be a bug, but that may be just because i have spent the last 5 hours ripping my hair out because i couldn't figure out what the hell was wrong with my code. HOWEVER... imagine some class called Object: class Object { var $key; var $count; function Object() { $this->key = rand(); } function someMethod() { $this->count = $this->key++; } function keyMethod() { return $this->key; } } now consider the following piece of code: $all_obj = array(); for($i = 0;$i<10;$i++) { $cur_obj = new Object(); $all_vars[$cur_obj->keyMethod()] = &$cur_obj;//some unique key $cur_obj->someMethod(); //changes $cur_obj in some way } if you were to run this code, you would get an array with ten elements, each with an array key corresponding to the random integer produced by the rand() function in the Object classes constructor. HOWEVER: (and this is the absolute killer here) each of the elements of the array will point to THE SAME instance of Object - ie. if you were to print out the $count variable of each instance of Object in the array, they would all be the same value. why? well, obviously the scope of the $cur_obj variable in the for loop above exists past the end of the for loop. to get around it, simply add the line: unset($cur_obj); at the bottom of the loop. as mentioned in the previous manual section, this will not unset the element in the $all_obj array, but will merely unlink the $cur_obj variable's reference to it. i would have thought that this would happen automatically. GEEZ I WISH I HAD KNOWN THAT EARLIER!!! hope this helps someone. ---- Manual Page -- http://www.php.net/manual/en/language.references.unset.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39776 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39776&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39776&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#64948) next »