我正在使用PHP 7.1.11
在 PHP 手册中,我遇到了一些非常不同的代码,如下所示:
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign a reference to the static variable
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign the object to the static variable
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
上述代码的输出如下:
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}
我根本不理解上面的代码,因为在我的职业生涯中,我第一次看到在其函数定义中的函数名称前面有一个引用。因此,从第一行本身开始,代码就让我度过了一生的艰难时光。
有人请在上面的代码中解释一下这里发生了什么?
在函数定义中使用引用的目的是什么?这种编码风格不会让简单的事情变得困难吗?
根据当前可用的PHP 编码标准,这是一种有效的编码风格吗?