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
This is a function that returns by reference — the term “passing a function by reference” is a bit misleading:
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:
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).