praveenhotha Posted July 14, 2008 Share Posted July 14, 2008 Can anyone please explain the following code snippet. I was expecting the output to be 0,1,2,3,4 ?? ??? <? class AnyClass { public $member; public function __construct($val) { $this->member = $val; } } $manyObjects = array(); $obj = null; for($i = 0; $i < 5;$i++) { $obj = new AnyClass($i); // create new instance $manyObjects[] = &$obj; } for($i = 0; $i < 5;$i++) { echo "<br>Value:".$manyObjects[$i]->member."\r\n"; } ?> Output : 4 4 4 4 4 Link to comment https://forums.phpfreaks.com/topic/114662-passing-an-object-reference/ Share on other sites More sharing options...
MiCR0 Posted July 14, 2008 Share Posted July 14, 2008 Error with : $manyObjects[] = &$obj; Should be $manyObjects[] = $obj; Link to comment https://forums.phpfreaks.com/topic/114662-passing-an-object-reference/#findComment-589637 Share on other sites More sharing options...
praveenhotha Posted July 14, 2008 Author Share Posted July 14, 2008 It doesn't throw any error, but prints five 4s. Link to comment https://forums.phpfreaks.com/topic/114662-passing-an-object-reference/#findComment-589642 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.