There are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links for further reading.
PHP 的引用允许用两个变量来指向同一个内容。意思是,当这样做时:
<?php
$a =& $b;
?>
注意:
$a 和 $b 在这里是完全相同的,这并不是 $a 指向了 $b 或者相反,而是 $a 和 $b 指向了同一个地方。
注意:
如果对一个未定义的变量进行引用赋值、引用参数传递或引用返回,则会自动创建该变量。
示例 #1 对未定义的变量使用引用
<?php
function foo(&$var) { }
foo($a); // $a is "created" and assigned to null
$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)
$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
同样的语法可以用在返回引用的函数中:
<?php
$foo =& find_var($bar);
?>
如果在一个函数内部给一个声明为 global
的变量赋于一个引用,该引用只在函数内部可见。可以通过使用
$GLOBALS 数组避免这一点。
示例 #2 在函数内引用全局变量
<?php
$var1 = "Example variable";
$var2 = "";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // visible only inside the function
} else {
$GLOBALS["var2"] =& $var1; // visible also in global context
}
}
global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
global $var;
当成是 $var
=& $GLOBALS['var'];
的简写。从而将其它引用赋给
$var
只改变了本地变量的引用。
注意:
如果在 foreach 语句中给一个具有引用的变量赋值,被引用的对象也被改变。
示例 #3 引用与 foreach 语句
<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
// do something
}
echo $ref; // 3 - last element of the iterated array
?>
While not being strictly an assignment by reference, expressions created
with the language construct
array()
can also
behave as such by prefixing &
to the array element
to add. Example:
<?php
$a = 1;
$b = array(2, 3);
$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++; $arr[1]++; $arr[2]++;
/* $a == 2, $b == array(3, 4); */
?>
Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:
<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b
/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>
引用做的第二件事是用引用传递变量。这是通过在函数内建立一个本地变量并且该变量在呼叫范围内引用了同一个内容来实现的。例如:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
?>
引用做的第三件事是引用返回。