2012-06-19 206 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);