2012-06-19 211 views
2

那么,我知道什么是引用,什么时候使用是显而易见的。传递函数通过引用

我真的无法得到的一件事是,最好是通过引用传递函数。

<?php 

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

} 

为了避免混淆,还有就是一些例子如我所理解的参考,

<?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'); 

使用引用的所有好处是显而易见的我,除了使用“通过引用传递函数”

问题:当通过引用传递函数(我已经搜索答案在这里,但还不能掌握这个) 感谢

+0

我想这个问题属于http://programmers.stackexchange.com/ – acme

回答

3

这是一个函数,returns by reference - 术语“通过引用传递函数”是有点误导:

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

的用例是相当与正常参考相同,这是不常见的。对于(人为)例如,考虑的是,在阵列查找元素的函数:

$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

在上面的例子中,你已经在一个可重用的函数中封装了在数据结构中搜索一个项目的代码(实际上可能比这个数组复杂得多)。如果打算使用返回值来修改原始结构本身,除了从函数返回引用外没有别的选择(在这种情况下,您也可以将索引返回到数组中,但考虑没有索引的结构,如图)。

+0

很好的解释! – acme

1

你的意思是Returning References

一个简单的例子是:

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

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

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