Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

reference - PHP param by ref => assign to ref = NULL

I found a strange behavior when passing parameter by reference to an object method:

class Test
{
    private $value;
    public  function Set($value)
    {
        $this->value = $value;
    }

    public  function Get(&$ref)
    {
        $ref = &$this->value; //SET REF PARAMETER TO THIS VALUE BY REF
    }
}

$test = new Test();
$test->Set('test');
$test->Get($value1);

var_dump($value1); //NULL INSTEAD OF 'test'!

edit: GetByRef(...) name was wrong for this example, renamed to: Get(...)

edit2: I forgot the real test case where I stucked:

$test->Get($value1);
$test->Get($value2);

$value1 = 'Another test value';
echo $value2; //SHOULD BE SAME: 'Another test value';

$value2 does not know if value1 created or not, so the standard $value2 = &$value1 not works here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are assigning to a reference by reference. This is why you get null. It works fine if you assign normally:

public function GetByRef(&$ref) {
    $ref = $this->value;
}

By declaring &$ref in the method signature and calling the method, a variable is created in the calling scope with a default value of null, which is referenced inside the method as $ref. By doing $ref = &$this->value you are basically removing that reference and are creating a new reference $ref. Using =& always creates a new reference variable; if you want to change its value instead, you have to use = to assign to it. So the variable which was created in the calling scope remains set at its initial value null and its reference to $ref inside the method is broken.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...