繁体   English   中英

通过引用返回的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();

回声

Hello
Goodbye

通过引用返回仅在OOP上下文中有效吗?

不会。PHP不管是函数还是类方法都没有区别, 按引用返回始终有效。

您所询问的内容表明您可能还没有完全理解PHP中的引用,众所周知(可能众所周知)。 我建议您阅读PHP手册中的整个主题,以及至少两位来自不同作者的资料。 这是一个复杂的话题。

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

因此,这更多是您在此处提出的变量范围问题:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM