Problem with Object references in an array via for loop
| From: | David Moylan | Date: | Thu, 29 May 2008 16:31:31 +0000 |
| Subject: | Problem with Object references in an array via for loop | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-274821@lists.php.net to get a copy of this message | ||
I have a snippet of code like this which works fine in PHP4.
$secs = array();
foreach($_GET['sids'] as $sid){
$secs[$sid] = new CustomSecurity();
$secs[$sid]->set(array('customSecurityID' => $sid));
}
However, in PHP5 (5.2.4) the array has the proper keys in it but all of the array values in $secs seem to point to the same instance. Basically, the customSecurityID value inside each array value (object instance) should match the array key, but all of the customSecurityID values are set to the last $sid value during the final iteration which tells me the array values are not 3 separate instances, but references to the same instance.
I'm having a hard time seeing how this isn't a bug. On each iteration of the loop I'm using a new variable $secs[$sid] which is previously unassigned and assigning it via the new operator to a new instance.
Is this a bug or a strange reference behavior that I don't understand?
How can you fill arrays with multiple new instances?
Thanks.
Dave