&$变量和&功能的含义?
可能重复:
参考 - 这个符号在PHP中的含义是什么?
&$variable
的含义是什么?
和功能的意义
function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 )
{
$rs =& $this->do_query( $sql, $offset, $nrows, $inputarr);
return $rs;
}
像这样传递一个参数: myFunc(&$var);
意味着该变量通过引用传递(而不是通过值)。 因此,对函数中的变量所做的任何修改都会修改调用的变量。
把&
该函数名前指“参考收益”。 这有点违反直觉。 如果可能,我会避免使用它。 用&符号启动PHP函数是什么意思?
小心不要将它与&=
或&
运营商混淆,这是完全不同的。
通过引用传递快速测试:
<?php
class myClass {
public $var;
}
function incrementVar($a) {
$a++;
}
function incrementVarRef(&$a) { // not deprecated
$a++;
}
function incrementObj($obj) {
$obj->var++;
}
$c = new myClass();
$c->var = 1;
$a = 1; incrementVar($a); echo "test1 $an";
$a = 1; incrementVar(&$a); echo "test2 $an"; // deprecated
$a = 1; incrementVarRef($a); echo "test3 $an";
incrementObj($c); echo "test4 $c->varn";// notice that objects are
// always passed by reference
输出:
Deprecated: Call-time pass-by-reference has been deprecated; If you would like
to pass it by reference, modify the declaration of incrementVar(). [...]
test1 1
test2 2
test3 2
test4 2
和号 - “&” - 用于指定变量的地址,而不是其值。 我们称之为“通过参考”。
所以,“&$ variable”是变量的引用,而不是它的值。 并且“function&func(...)告诉函数返回返回变量的引用,而不是变量的副本。
也可以看看:
上一篇: meaning of &$variable and &function?
下一篇: What's difference?