我知道&
用于引用,我看过它用过:
$foo = &$bar;
或
function foo(&$bar) {...}
或
foreach($array as &$value) {...}
我知道&
在上述情况下的含义。
但我在CodeIgniter中看到了这个函数:
function &get_instance() {
return CI_Controller::get_instance();
}
之前我从未在函数名前面看过&
。 &
在上面的功能中做了什么?
答案 0 :(得分:5)
这称为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.
?>