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

时间:2013-07-30 16:25:54

标签: php

如果我尝试这段代码:

<?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上下文中工作吗?

2 个答案:

答案 0 :(得分:3)

这是因为当函数调用完成并且函数本地引用变量未设置时,函数的作用域会崩溃。对该函数的任何后续调用都会创建一个新的$ 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

答案 1 :(得分:0)

  

通过引用返回仅在OOP上下文中工作吗?

没有。如果它是函数或类方法,PHP没有区别,returning by reference总是有效。

你问的问题表明你可能还没有完全理解PHP中的哪些引用,哪些 - 我们都知道 - 可能发生。我建议你阅读PHP手册中的整个主题,以及不同作者至少两个来源。这是一个复杂的话题。

在你的例子中,请注意你在这里返回的参考顺序。在调用函数时,将$param设置为该值 - 始终 - 因此该函数返回对该新设置变量的引用。

所以这更像是你在这里要求的变量范围的问题: