PHP Returned Links

Return by reference is useful when you want to use a function to find which variable should be referenced . Don't use a backlink to improve performance. The engine will automatically optimize this for its own. Only return links when you have a valid technical reason to do so.

What does bold mean?

does this mean something like

public function & getHellos () {
    $ sql = 'SELECT id, greeting FROM #__hello';
    $ data = $ this -> _ getList ($ sql);
    return $ data;
}

where am i not bound to any variable?

+2


source to share


4 answers


We return by reference when we want the function to GetRef()

determine which variable $foo

or $bar

reference $foo_or_bar

should be linked:

$foo = "foo";
$bar = "bar";
function &GetRef(){
    global $foo, $bar;
    if(rand(0, 1) === 1){
        return $foo;
    }else{
        return $bar;
    }
}
$foo_or_bar =& GetRef();
$foo_or_bar = 'some other value';

var_dump($foo); // either one of this will be 'some other value'
var_dump($bar); // either one of this will be 'some other value'

      

Deryck Ethans also elaborated on this in PHP References: An In-Depth Look :



This [return by reference] is useful, for example, if you want to select a variable to modify using a function, for example by selecting an array element or node in a tree structure.

Sample code demonstrating selection of an array element via return-by-reference:

function &SelectArrayElement(&$array, $key){
    return $array[$key];
}

$array = array(0, 1, 2);
$element =& SelectArrayElement($array, 0);
$element = 10;
var_dump($array); // array(10, 1, 2)

      

+4


source


Na. You cannot pass a reference to a function name. When passing a variable by reference, if you change its value in your function, that value will also be changed outside the function.

For example:

function test(&$var) {
    $var = strtolower($var);
}

function second_test($var) {
    $var = strtolower($var);
}

$var = 'PHP';

second_test($var);
echo $var;

echo "\r\n";

test($var);
echo $var;

      



This will display:

PHP
php

      

Since the second_test method does not have a variable passed by reference, the updated value is updated only inside the function. But the test method is passed by reference as a variable. This way the value will be updated inside and outside this function.

+2


source


I believe referring to byref arguments is not functions. For example:

function doStuff(&$value1, &$value2) {
    ...
}
      

is an acceptable use of byref because the doStuff () function must return 2 values. If it's just doStuff () only needed to affect one value, it would be more elegant if the function returned it, by value, of course.

0


source


The bold part means this is useful if you want to store a reference to a variable instead of the value of that variable.

The link return example , on php.net, explains it pretty well, IMO.

0


source







All Articles