2013-02-27 75 views
6

我在旅途中看到過創建和創建一些我的php應用程序,&符號,它們位於變量和類名前面。PHP參考資料:瞭解

據我所知,這些都是PHP的參考文獻,但我所看到和看到的文檔似乎只是沒有以我理解或混淆的方式解釋它。你怎麼能解釋下面的例子,我已經看到讓他們更容易理解。

public static function &function_name(){...} 

    $varname =& functioncall(); 

    function ($var, &$var2, $var3){...} 

非常感謝

+0

看到它http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php'=&References'塊。 – Winston 2013-02-27 18:23:13

回答

4

比方說,你有兩個功能

$a = 5; 
function withReference(&$a) { 
    $a++; 
} 
function withoutReference($a) { 
    $a++; 
} 

withoutReference($a); 
// $a is still 5, since your function had a local copy of $a 
var_dump($a); 
withReference($a); 
// $a is now 6, you changed $a outside of function scope 
var_dump($a); 

所以,通過引用傳遞參數允許函數修改它的功能範圍之外。

現在的第二個例子。

你必須返回一個參考

class References { 
    public $a = 5; 
    public function &getA() { 
     return $this->a; 
    } 
} 

$references = new References; 
// let's do regular assignment 
$a = $references->getA(); 
$a++; 
// you get 5, $a++ had no effect on $a from the class 
var_dump($references->getA()); 

// now let's do reference assignment 
$a = &$references->getA(); 
$a++; 
// $a is the same as $reference->a, so now you will get 6 
var_dump($references->getA()); 

// a little bit different 
$references->a++; 
// since $a is the same as $reference->a, you will get 7 
var_dump($a); 
+1

@ Marko D很多感謝以上,我想明白,所以如果它是任何目前的項目的任何用途,如果不是一個心靈,但爲未來的。 – 2013-02-27 21:37:30

0

參考功能

$name = 'alfa'; 
$address = 'street'; 
//declaring the function with the $ tells PHP that the function will 
//return the reference to the value, and not the value itself 
function &function_name($what){ 
//we need to access some previous declared variables 
GLOBAL $name,$address;//or at function declaration (use) keyword 
    if ($what == 'name') 
     return $name; 
    else 
     return $address; 
} 
//now we "link" the $search variable and the $name one with the same value 
$search =& function_name('name'); 
//we can use the result as value, not as reference too 
$other_search = function_name('name'); 
//any change on this reference will affect the "$name" too 
$search = 'new_name'; 
var_dump($search,$name,$other_search); 
//will output string 'new_name' (length=8)string 'new_name' (length=8)string 'alfa' (length=4) 

通常使用的方法與實施相同的接口對象,你要選擇你要的對象的函數與下一個合作。

通過引用傳遞:

function ($var, &$var2, $var3){...} 

我敢肯定,你看到的例子,所以我就解釋如何以及何時使用它。 基本情況是,您何時需要應用於當前對象/數據的大邏輯,並且不希望在內存中製作更多副本。 希望這有助於。

+0

非常感謝。 – 2013-02-27 21:36:21