[英]PHP returning by reference not working with normal functions but working with OOP
如果我尝试此代码:
<?php
class ref
{
public $reff = "original ";
public function &get_reff()
{
return $this->reff;
}
public function get_reff2()
{
return $this->reff;
}
}
$thereffc = new ref;
$aa =& $thereffc->get_reff();
echo $aa;
$aa = " the changed value ";
echo $thereffc->get_reff(); // says "the changed value "
echo $thereffc->reff; // same thing
?>
然后按引用返回,对象属性$reff
的值随着引用它的变量$aa
变化而改变。
但是,当我在不在类内的普通函数上尝试此操作时,它将无法正常工作!
我尝试了这段代码:
<?php
function &foo()
{
$param = " the first <br>";
return $param;
}
$a = & foo();
$a = " the second <br>";
echo foo(); // just says "the first" !!!
它看起来像函数foo()
识别它通过引用返回,并且顽固地返回它想要的!
通过引用返回仅在OOP上下文中有效吗?
这是因为当函数调用完成并且未设置对变量的函数本地引用时,函数的作用域就会崩溃。 随后对该函数的任何调用都会创建一个新的$ param变量。
即使在函数中不是这种情况,您也会在每次调用函数时将变量重新分配给the first <br>
。
如果要证明按引用返回有效,请使用static关键字为函数变量赋予持久状态。
看这个例子
function &test(){
static $param = "Hello\n";
return $param;
}
$a = &test();
echo $a;
$a = "Goodbye\n";
echo test();
回声
Hello
Goodbye
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.