简体   繁体   中英

PHP returning by reference not working with normal functions but working with OOP

If I try this code :

<?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
?>

Then returning by reference works and the value of the object property $reff gets changed as the variable $aa that references it changes too.

However, when I try this on a normal function that is not inside a class, it won't work !!

I tried this code :

<?php

function &foo()
{
    $param = " the first <br>";
    return $param;
}

$a = & foo();

$a = " the second <br>";

echo foo(); // just says "the first" !!!

it looks like the function foo() wont recognize it returns by reference and stubbornly returns what it wants !!!

Does returning by reference work only in OOP context ??

That is because a function's scope collapses when the function call completes and the function local reference to the variable is unset. Any subsequent calls to the function create a new $param variable.

Even if that where not the case in the function you are reassigning the variable to the first <br> with each invocation of the function.

If you want proof that the return by reference works use the static keyword to give the function variable a persistent state.

See this example

function &test(){
    static $param = "Hello\n";
    return $param;
}


$a = &test();
echo $a;
$a = "Goodbye\n";

echo test();

Echo's

Hello
Goodbye

Does returning by reference work only in OOP context ??

No. PHP makes no difference if that is a function or a class method, returning by reference always works.

That you ask indicates you might have not have understood fully what references in PHP are, which - as we all know - can happen. I suggest you read the whole topic in the PHP manual and at least two more sources by different authors. It's a complicated topic.

In your example, take care which reference you return here btw. You set $param to that value - always - when you call the function, so the function returns a reference to that newly set variable.

So this is more a question of variable scope you ask here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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