RE: note 39776 rejected and deleted from language.references.unset by notes editor didou

From: Date: Tue, 10 Feb 2004 13:54:54 +0000
Subject: RE: note 39776 rejected and deleted from language.references.unset by notes editor didou
Groups: php.mirrors 
Request: Send a blank email to php-mirrors+get-23411@lists.php.net to get a copy of this message
below is a copy of the note. it is not a bug report, a feature request, or a support request, but merely a statement that something works in a way that i would not have expected it to work, and i am letting others know that this is the case. i have included the note below. please re-include it in the online manual as i think it is a worthy piece of information that may save someone some time in the future. sincerely, iain dooley ----------------------------------------------- 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.

« previous php.mirrors (#23411) next »