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
}
user3791372
  • 4,445
  • 6
  • 44
  • 78
  • *"if I pass an object to a function in PHP, it's passed by reference"* -- this is not correct. Read the differences: http://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. – axiac Sep 14 '17 at 10:37
  • 1
    Possible duplicate of [Are PHP5 objects passed by reference?](https://stackoverflow.com/questions/2715026/are-php5-objects-passed-by-reference) – iainn Sep 14 '17 at 10:38

2 Answers2

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();
}
Pieter van den Ham
  • 4,381
  • 3
  • 26
  • 41
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; 
}
Youssef Saoubou
  • 591
  • 4
  • 11
  • 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). – TobyG Apr 12 '21 at 16:01