Voting

: seven plus two?
(Example: nine)

The Note You're Voting On

mchljnk at NOSPAM dot gmail dot com
11 years ago
Using objects with array_fill may cause unexpected results. Consider the following:

<?php
class Foo {
public
$bar = "banana";
}

//fill an array with objects
$array = array_fill(0, 2, new Foo());

var_dump($array);
/*
array(2) {
[0]=>
object(Foo)#1 (1) {
["bar"]=>
string(6) "banana"
}
[1]=>
object(Foo)#1 (1) {
["bar"]=>
string(6) "banana"
}
} */

//now we change the attribute of the object stored in index 0
//this actually changes the attribute for EACH object in the ENTIRE array
$array[0]->bar = "apple";

var_dump($array);
/*
array(2) {
[0]=>
object(Foo)#1 (1) {
["bar"]=>
string(5) "apple"
}
[1]=>
object(Foo)#1 (1) {
["bar"]=>
string(5) "apple"
}
}
*/
?>

Objects are filled in the array BY REFERENCE. They are not copied for each element in the array.

<< Back to user notes page

To Top