PHP object arguments behaviour

756

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 should not modify the original object so why does this happen?

217

Answer

Solution:

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 . 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;
690

Answer

Solution:

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

People are also looking for solutions to the problem: php - Symfony Routing: sf_format default value

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.