chức năng tham khảo
$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)
Thông thường bạn sử dụng phương pháp này với đối tượng mà thực hiện cùng một giao diện, và bạn muốn chọn đối tượng bạn muốn để làm việc tiếp theo.
Đi qua bằng cách tham khảo:
function ($var, &$var2, $var3){...}
tôi chắc chắn rằng bạn đã thấy các ví dụ, vì vậy tôi sẽ chỉ giải thích như thế nào và khi nào thì sử dụng nó. Kịch bản cơ bản là khi nào bạn có một logic lớn mà bạn muốn áp dụng cho một đối tượng/dữ liệu hiện tại và bạn không muốn tạo thêm bản sao của nó (trong bộ nhớ). Hy vọng điều này sẽ hữu ích.
Nguồn
2013-02-27 18:54:41
Xem khối http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php '= & Tham chiếu'. – Winston