Jump to content

PHP5 passing-by-reference


ironhoof

Recommended Posts

Hi,

Can someone please point out if the following is correct behaviour for PHP 5.2.0, because it's truly puzzling me ...

[code]
// Class file
class MyModifier {
  static public function modify($model) {
    $anotherModel = getSingletonModelFromSomewhere();
    $model = $anotherModel;
  }
}

// Calling script
$M = new MyModel();
MyModifier::modify($M);
print $M===getSingletonModelFromSomewhere() ? 'SAME' : 'DIFF';    // This prints 'DIFF', but I would expect it to print 'SAME'
[/code]

What MyModifier::modify() is doing is replacing the instance passed to it with a different instance as returned by "getSingletonModelFromSomewhere()".

However, it seems that $M is not being replaced at all and is instead being cloned.

To my surprise, changing the method declaration to ...

[code]
static public function modify(&$model) { ... }
[/code]

... makes it work fine!

This surprises me because i thought PHP5 passes objects by reference automatically, but it appears not to be the case here and it requires the ampersand "&" to tell it we're passing by ref. This seems pretty buggy to me.

Is this correct behaviour?
Link to comment
https://forums.phpfreaks.com/topic/36370-php5-passing-by-reference/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.