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?
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:
Or assign it to a reference argument, then call it like so:
Answer
Solution:
Classes attributes in php (as well as other languages like javascript) are always passed as references