8

可能重复:
参考 - 这个符号在 PHP 中是什么意思?

函数的含义&$variable
和含义是什么

function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 )
{
    $rs =& $this->do_query( $sql, $offset, $nrows, $inputarr);
    return $rs;
} 
4

2 回答 2

8

像这样传递参数:myFunc(&$var);意味着变量是通过引用传递的(而不是通过值传递)。因此,对函数中的变量所做的任何修改都会修改进行调用的变量。

放在&函数名之前意味着“通过引用返回”。这有点违反直觉。如果可能的话,我会避免使用它。用 & 符号启动 PHP 函数是什么意思?

注意不要与&=or&运算符混淆,这是完全不同的

通过引用快速测试:

<?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 $a\n";
$a = 1; incrementVar(&$a);   echo "test2 $a\n"; // deprecated
$a = 1; incrementVarRef($a); echo "test3 $a\n";
        incrementObj($c);    echo "test4 $c->var\n";// 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
于 2012-10-21T21:19:24.007 回答
2

与号 - “&” - 用于指定变量的地址,而不是它的。我们称之为“通过引用传递”。

所以,“&$variable”是对变量的引用,而不是它的值。而 "function &func(..." 告诉函数返回返回变量的引用,而不是变量的副本。

也可以看看:

于 2012-10-21T21:19:35.157 回答