meaning of &$variable and &function?

Possible Duplicate:
Reference - What does this symbol mean in PHP?

what is the meaning of &$variable
and meaning of functions like

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

Passing an argument like so: myFunc(&$var); means that the variable is passed by reference (and not by value). So any modifications made to the variable in the function modify the variable where the call is made.

Putting & before the function name means "return by reference". This is a bit very counter-intuitive. I would avoid using it if possible. What does it mean to start a PHP function with an ampersand?

Be careful not to confuse it with the &= or & operator, which is completely different.

Quick test for passing by reference:

<?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

Output:

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

The ampersand - "&" - is used to designate the address of a variable, instead of it's value. We call this "pass by reference".

So, "&$variable" is the reference to the variable, not it's value. And "function &func(..." tells the function to return the reference of the return variable, instead of a copy of the variable.

See also:

  • difference between function and &function
  • http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference
  • http://www.php.net/manual/en/language.references.pass.php
  • http://www.adp-gmbh.ch/php/pass_by_reference.html
  • 链接地址: http://www.djcxy.com/p/57256.html

    上一篇: 在PHP5中是否有引用返回的有效技术用途?

    下一篇: &$变量和&功能的含义?