php - 函数名前面的 & 的作用是什么?

标签 php codeigniter

我知道 & 用于引用,并且我见过它的用法如下:

$foo = &$bar;

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

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

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


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

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

我以前从未在函数名称前面见过&& 在上面的函数中做了什么?

最佳答案

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

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

?>

关于php - 函数名前面的 & 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281070/

相关文章:

laravel - 如何在 codeigniter 或 laravel 中使用 hash_hmac 函数?

php - Laravel - selectRaw( count(*) ) 返回为字符串而不是整数?

php - 使用 GD 库编写印地语字体未按预期呈现

php - 选择最接近变量的值

php - 如何从 CodeIgniter 中的模型加载助手?

php - 数据库查询结果codeigniter后无法调用php函数

php - CodeIgniter(预 Controller ) Hook 和缓存

php - 在帖子表中显示类别和标签(一对多关系)

javascript - 查询结果到json laravel 5

php - 如何理解qcachegrind结果?