ironhoof Posted January 30, 2007 Share Posted January 30, 2007 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 fileclass 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.