For Programmers: Free Programming Magazines  


Home > Archive > PHP Mirrors > March 2004 > RE: note 39776 rejected and deleted from language.references.unset









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author RE: note 39776 rejected and deleted from language.references.unset
Iain Dooley

2004-03-19, 1:04 pm

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.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com