Jump to content

Return by reference


doebaladoo

Recommended Posts

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

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

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.