PHP通过引用返回,不使用普通函数,但使用OOP


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();

Echo的

Hello
Goodbye

引用返回是否仅在OOP环境下有效??

没有。无论是函数还是类方法,PHP都没有区别,通过引用返回总是有效的。

你问这个问题表明你可能还没有完全理解PHP中的引用是什么,众所周知,这是可能发生的。我建议您阅读PHP手册中的整个主题,以及不同作者的至少两个以上来源。这是一个复杂的话题。

在您的示例中,请注意您在此处返回的引用btw。当您调用该函数时,您将$param设置为该值(始终),因此该函数将返回对新设置的变量的引用。

所以这更多的是一个可变范围的问题,你在这里问:

  • 变量范围