0

if I pass an object to a function in PHP, it's passed by reference, and if I set that object to a new object, it doesn't 'stick'. How can I assign a new object to an object that's passed in preferably without iterating over all properties?

e.g.:

function Foo($obj)
{
    // do stuff and create new obj
    $obj = $newObj;

    // upon function exit, the original $obj value is as it was
}
2
  • "if I pass an object to a function in PHP, it's passed by reference" -- this is not correct. Read the differences: php.net/manual/en/language.oop5.references.php. If you want to pass an object to the function and want the function to be able to replace the object then you have to use a reference. Or, better, let the function return another object and do the replacement in the calling code. Commented Sep 14, 2017 at 10:37
  • 1
    Possible duplicate of Are PHP5 objects passed by reference? Commented Sep 14, 2017 at 10:38

2 Answers 2

2

if I pass an object to a function in PHP, it's passed by reference

In PHP an object is passed by "pointer-value" e.g. a pointer to the object is copied into the function arguments:

function test($arg) {
    $arg = new stdClass();
}

$a = new stdClass();
$a->property = '123';
test($a);

var_dump($a->property); // "123"

To pass by pointer-reference, prefix an ampersand sign to the parameter:

function test(&$arg) {
    $arg = new stdClass();
}

$a = new stdClass();
$a->property = '123';
test($a);

var_dump($a->property); // Undefined property

But you should avoid pointer-references as they tend to confuse and instead just return the new object:

function test($arg) {
    return new stdClass();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you need to return the new value then you can access the new value:

function Foo($obj)
{
    // do stuff and create new obj
    $obj = $newObj;

    // upon function exit, the original $obj value is as it was
    return $obj; 
}

1 Comment

This will just return a variable that also still points to the original object. To return a new instance you need to clone the object otherwise there is little benefit to returning the object here (other than nicer to read code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.