开发者

What's the benefit of function refrence?

开发者 https://www.devze.com 2022-12-22 21:33 出处:网络
When I reading the code of CodeIgniter,I found some functions written as follows: function &get_instance()

When I reading the code of CodeIgniter,I found some functions written as follows:

function &get_instance()
{
   global $CI, $OBJ;

   if (is_object($CI))
   {
       return $CI;
   }

   return $OBJ->load;
}

I can understand variable refrence,but I can hardly get this through.Is it necess开发者_StackOverflow社区ary to use this function style?And any benefit?

Thanks.


In PHP's syntax, this means that the function returns a reference instead of a value. For example:

<?php

$foo = 'foo';

function & get_foo_ref ()
{
    global $foo;
    return $foo;
}

// Get the reference to variable $foo stored into $bar
$bar = & get_foo_ref();
$bar = 'bar';

echo $foo; // Outputs 'bar', since $bar references to $foo.

?>

In the above example, removing the & from the function decleration would make the $foo variable still contain 'foo', since only the value, not the reference was returned from the function.

This was used more often in PHP4, because it did not pass objects by their reference and cloned them instead. Because of this, object variables had to be passed by reference to avoid unwanted cloning. This is no longer the case in PHP5 and references should not be used for this purpose.

However, functions that return references are not completely useless either (or bad practice, when not used for replacing object references). For example, personally I've used them when creating a script that passes a "path" to an function, which returns reference to variable in that path allowing me to set value to it and read the value. Due to recursive nature of the function, returning the reference was needed.


It is the same concept as variable reference, in fact this "style" is required when you want to return a REFERENCE to a variable and not the value itself.

Explained in the manual here: http://www.php.net/manual/en/functions.returning-values.php


no, there's no benefit. It was necessary for php4, but in php5 it's a bad practice.

0

精彩评论

暂无评论...
验证码 换一张
取 消