开发者

PHP object arguments behaviour

开发者 https://www.devze.com 2023-02-11 01:46 出处:网络
Take this situation: function edit($var) { $var->test = \"foo\"; } $obj = new stdClass; edit($obj); echo $obj->test; //\"foo\"

Take this situation:

function edit($var)
{
    $var->test = "foo";
}

$obj = new stdClass;
edit($obj);

echo $obj->test; //"foo"

The edit function does not take the argument as a reference and it shou开发者_StackOverflowld not modify the original object so why does this happen?


Because in PHP 5, references to objects are passed by value, as opposed to the objects themselves. That means your function argument $var and your calling-scope variable $obj are distinct references to the same object. This manual entry may help you.

To obtain a (shallow) copy of your object, use clone. In order to retrieve this copy, though, you need to return it:

function edit($var)
{
    $clone = clone $var;
    $clone->test = "foo";
    return $clone;
}

$obj = new stdClass;
$obj2 = edit($obj);

echo $obj2->test;

Or assign it to a reference argument, then call it like so:

function edit($var, &$clone)
{
    $clone = clone $var;
    $clone->test = "foo";
}

$obj = new stdClass;
edit($obj, $obj2);

echo $obj2->test;


Classes attributes in php (as well as other languages like javascript) are always passed as references

0

精彩评论

暂无评论...
验证码 换一张
取 消