On 11 May 2011 22:39, Richard S. Crawford <[email protected]> wrote:
> On Wed, May 11, 2011 at 1:30 PM, Peter Lind <[email protected]> wrote:
>>
>> On 11 May 2011 22:23, Richard S. Crawford <[email protected]> wrote:
>> > I'm encountering what appears to be a bug in array_push when I try using
>> > that function to add objects to an array. For example...
>> >
>> > A = Object 1
>> > B = Object 2
>> >
>> > 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
>> >
>> > Can anyone enlighten me as to why this is happening? I've looked through
>> > bug
>> > reports but haven't found anything, which leads me to think that perhaps
>> > my
>> > own code is at fault.
>> >
>>
>> If you could post some more of your code, it would be easier to check
>> if your code is at fault or not.
>>
>> Regards
>> Peter
>
> Here's some more sample code, then:
>
> ============================
> function retrieve_records ($where) {
> (Returns an array of objects which represent rows from a database
> query)
> }
>
> $records = retrieve_records($condition);
>
> $recordlist = array();
>
> foreach ($records as $record) {
>
> array_push ($recordlist, $record)
>
> }
> ============================
>
> I know this code isn't very useful, but these are the conditions which cause
> the issue I've mentioned.
class a {
public function __construct() {
$this->rand = mt_rand();
}
}
function retrieve_records () {
return array(
new a,
new a,
new a,
new a,
new a,
);
}
$records = retrieve_records();
$recordlist = array();
foreach ($records as $record) {
array_push ($recordlist, $record);
}
die(var_dump($recordlist));
gives me:
array(5) {
[0]=>
object(a)#1 (1) {
["rand"]=>
int(515141845)
}
[1]=>
object(a)#2 (1) {
["rand"]=>
int(804365869)
}
[2]=>
object(a)#3 (1) {
["rand"]=>
int(32698894)
}
[3]=>
object(a)#4 (1) {
["rand"]=>
int(1375725959)
}
[4]=>
object(a)#5 (1) {
["rand"]=>
int(100662005)
}
}
I'd say there's a problem in your code. Check where you might be using
references, chances are you're using one somewhere and not unsetting
it afterwards.
Regards
Peter
--
<hype>
WWW: plphp.dk / plind.dk
LinkedIn: plind
BeWelcome/Couchsurfing: Fake51
Twitter: kafe15
</hype>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php