的目的是什么?在函数名前面


What is the purpose of & in front of a function name?

我知道&是用于引用的,我看到它被这样使用:

$foo = &$bar;

function foo(&$bar) {...}

foreach($array as &$value) {...}

我知道&在上述情况下意味着什么。


但是我在CodeIgniter中看到了这个函数:

function &get_instance() {
    return CI_Controller::get_instance();
}

我从来没有在函数名前面看到过&&在上述功能中起什么作用?

这被称为returning by reference,它只是将返回值绑定到您分配给它的变量。在手册中有一个明确的例子:

<?php
    class foo {
        public $value = 42;
        public function &getValue() {
            return $this->value;
        }
    }
    $obj = new foo();
    $myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
    $obj->value = 2;
    echo $myValue;                // prints the new value of $obj->value, i.e. 2.
?>