doebaladoo Posted July 14, 2009 Share Posted July 14, 2009 I was thought that (when returning by reference) you should always add a & when assigning the return value. For instance: function & a () { } $a = & a(); and not: $a = a(); The follow works hower (without the added & ): class a { public $a = 1; } class b { static $var; public static function & gvar($i) { if(!(isset(b::$var[$i]))) { b::$var[$i] = new a; } return b::$var[$i]; } } $b = new b; $a = b::gvar(1); $a->a = 14; $c = b::gvar(1); echo $c->a; // 14 Notice the $a = b::gvar(1); without the &. Am I missing something??? Link to comment https://forums.phpfreaks.com/topic/165966-return-by-reference/ Share on other sites More sharing options...
J.Daniels Posted July 14, 2009 Share Posted July 14, 2009 In the function definition, you are specifying that it return by reference: public static function & gvar($i) { This is from Passing By References in the PHP manual Link to comment https://forums.phpfreaks.com/topic/165966-return-by-reference/#findComment-875345 Share on other sites More sharing options...
genericnumber1 Posted July 14, 2009 Share Posted July 14, 2009 Daniels, I think he knows that. doebaladoo, as of php5 all objects are passed by reference (they're instantiated on the heap if that means anything to you), so even specifying that the method returns a reference is not needed. Try removing the & from the function prototype and you should still get the same result. Link to comment https://forums.phpfreaks.com/topic/165966-return-by-reference/#findComment-875348 Share on other sites More sharing options...
doebaladoo Posted July 14, 2009 Author Share Posted July 14, 2009 Thanks genericnumber1! That solves it. I didn't even know that. I was struggling with the &'s all the time. Link to comment https://forums.phpfreaks.com/topic/165966-return-by-reference/#findComment-875406 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.