php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #34053 Objects in array don't behave as expected when passed by value
Submitted: 2005-08-09 19:19 UTC Modified: 2005-08-09 23:01 UTC
From: davelo36net at netscape dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.0.4 OS: Win XP SP2
Private report: No CVE-ID: None
 [2005-08-09 19:19 UTC] davelo36net at netscape dot net
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
        )

)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-08-09 23:01 UTC] sniper@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Jun 18 14:01:31 2024 UTC