PHP参数由ref =>分配给ref = NULL [英] PHP param by ref => assign to ref = NULL

查看:62
本文介绍了PHP参数由ref =>分配给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'!

此示例中的GetByRef(...)名称错误,重命名为:Get(...)

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

edit2:我忘了卡住的真实测试用例:

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不知道是否创建了value1,因此标准的$ value2 =& $ value1在这里不起作用.

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

推荐答案

您正在通过引用分配给引用.这就是为什么您得到null的原因.如果您正常分配,效果很好:

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;
}

通过在方法签名中声明&$ref并调用该方法,将在调用范围中创建一个变量,其默认值为null,该变量在方法内部被称为$ref.通过执行$ref = &$this->value,您基本上将删除该引用,并创建一个新的引用$ref.使用=&总是会创建一个新的参考变量.如果要更改其值,则必须使用=进行分配.因此,在调用范围内创建的变量将保持其初始值null的设置,并且该方法内部对$ref的引用将被破坏.

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.

这篇关于PHP参数由ref =>分配给ref = NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆