Yang
Yang

Reputation: 8701

pass function by reference

Well, I know what references are and when it's use is obvious.

One thing I really can't get is that when it's better to pass function by reference.

<?php

//right here, I wonder why and when
function &test(){

}

To avoid confusion, there're some examples as how I understand the references,

<?php

$numbers = array(2,3,4);

foreach ($numbers as &$number){
   $number = $number * 2;
}

// now numbers is $numbers = array(4,6,8);


$var = 'test';
$foo = &var; //now all changes to $foo will be affected to $var, because we've assigned simple pointer 



//Similar to array_push()
function add_key(&$array, $key){
  return $array[$key];
}

//so we don't need to assign returned value from this function
//we just call this one

$array = array('a', 'b');

add_key($array,'c');
//now $array is ('a', 'b', 'c');

All benefits of using the references are obvious to me, except the use of "passing function by reference",

Question: When to pass function by reference (I've searched answer here, but still can't grasp this one) Thanks

Upvotes: 2

Views: 142

Answers (2)

Jon
Jon

Reputation: 437386

This is a function that returns by reference -- the term "passing a function by reference" is a bit misleading:

function &test(){
    return /* something */;
}

The use cases are pretty much the same as for normal references, which is to say not common. For a (contrived) example, consider a function that finds an element in an array:

$arr = array(
    array('name' => 'John', 'age' => 20),
    array('name' => 'Mary', 'age' => 30),
);

function &findPerson(&$list, $name) {
    foreach ($list as &$person) {
        if ($person['name'] == $name) {
            return $person;
        }
    }
    return null;
}

$john = &findPerson($arr, 'John');
$john['age'] = 21;

print_r($arr); // changing $john produces a visible change here

See it in action.

In the above example, you have encapsulated the code that searches for an item inside a data structure (which in practice could be a lot more complicated than this array) in a function that can be reused. If you intend to use the return value to modify the original structure itself there's no other option than returning a reference from the function (in this specific case you could also have returned an index into the array, but think about structures that do not have indexes, e.g. graphs).

Upvotes: 3

xdazz
xdazz

Reputation: 160843

Do you means Returning References ?

A simple example is:

function &test(&$a){
  return $a;
}

$a = 10;
$b = &test($a);
$b++;

// here $a became 11
var_dump($a);

Upvotes: 1

Related Questions