Re: Odd array_push issue

From: Date: Wed, 11 May 2011 20:33:43 +0000
Subject: Re: Odd array_push issue
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-312771@lists.php.net to get a copy of this message
On Wed, May 11, 2011 at 1:23 PM, Richard S. Crawford <richard@underpope.com>wrote: > If I execute the following code: > > array_push(objectarray, A); > array_push(objectarray, B); > > ...I expect the contents of $objectarray to be: > > [0] = A > [1] = B > > Instead, the last object pushed onto the array is repeated throughout the > array. In other words, instead of the above, I get this: > > [0] = B > [1] = B > It appears to be a problem with references. Are you using a reference in a loop? Can you paste your actual code? It works fine for me: php > class Foo { public $name; function __construct($name) { $this->name = $name; } function __toString() { return $this->name; } } php > $a = new Foo('A'); php > $b = new Foo('B'); php > $x = array(); php > array_push($x, $a); php > array_push($x, $b); php > var_dump($x); array(2) { [0]=> object(Foo)#1 (1) { ["name"]=> string(1) "A" } [1]=> object(Foo)#2 (1) { ["name"]=> string(1) "B" } } David

« previous php.general (#312771) next »