note 113647 added to function.array-fill

From: Date: Sun, 10 Nov 2013 03:07:09 +0000
Subject: note 113647 added to function.array-fill
Groups: php.notes 
Request: Send a blank email to php-notes+get-197481@lists.php.net to get a copy of this message
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. ---- Server IP: 192.41.45.150 Probable Submitter: 99.177.64.34 ---- Manual Page -- http://php.net/manual/en/function.array-fill.php Edit -- https://master.php.net/note/edit/113647 Del: integrated -- https://master.php.net/note/delete/113647/integrated Del: useless -- https://master.php.net/note/delete/113647/useless Del: bad code -- https://master.php.net/note/delete/113647/bad+code Del: spam -- https://master.php.net/note/delete/113647/spam Del: non-english -- https://master.php.net/note/delete/113647/non-english Del: in docs -- https://master.php.net/note/delete/113647/in+docs Del: other reasons-- https://master.php.net/note/delete/113647 Reject -- https://master.php.net/note/reject/113647 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#197481) next »