|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2005-08-09 23:01 UTC] sniper@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 08 19:00:01 2025 UTC |
Description: ------------ When one passes an array containing fundamental data types (ie strings, numbers, etc.) by value into a function that then modifies the value of said elements in its scope, the values of the array does not change in the scope of the calling procedure. However, when one passes an array containing user defined classes into a function that modifies the values of the objects in the array, the values of the objects in the array changes when the script returns to the calling procedure. A workaround is possible by serializing the array before the function that modifies the array locally is called and unserialing the array after the function is called, but that is wasteful of CPU resources compared to just giving the function a true local copy of the array and its elements (which should use about the same amount of memory as the serialization workaround). Reproduce code: --------------- <?php class foo { public $x; public function __construct($x) { $this->x=$x; } } function bar($x) { foreach($x as $y) $y->x++; } $array = array(new foo(1), new foo(2), new foo(3)); bar($array); print_r($array); ?> Expected result: ---------------- Array ( [0] => foo Object ( [x] => 1 ) [1] => foo Object ( [x] => 2 ) [2] => foo Object ( [x] => 3 ) ) Actual result: -------------- Array ( [0] => foo Object ( [x] => 2 ) [1] => foo Object ( [x] => 3 ) [2] => foo Object ( [x] => 4 ) )