【问题标题】:Why I cannot assign $this by value, it aparently is assigned by reference always?为什么我不能按值分配 $this,它总是按引用分配?
【发布时间】:2017-03-04 10:56:18
【问题描述】:

下面的代码解释了我遇到的问题,我试图通过值将$this 分配给一个变量,但它显然最终是通过引用分配的,为什么?我该怎么做?

以下脚本是一组TestTestQuery 两个类。 Test 假定$num 属性中的一个值,然后脚本调用Test->exist(),创建两个变量:$original“按值”和$obj 按引用,此时两者相同。最后脚本调用TestQuery->doit( $obj );假设TestQuery会修改$obj$code,如果$num的值为2,但结果无效,因为exist()方法中$original$obj的值是新的一样。

<?php

class TestQuery{
    public function doit( &$obj )
    {
        if ($obj->getNum() == 2)
            $obj->setCode( 55 );
    }
}

class Test {
    public $code;
    public $num;

    public function setCode( $code ) { $this->code= $code; }
    public function getCode( $code ) { return $this->code; }

    public function getNum()
    {
        return $this->num;
    }

    public function exist()
    {
        $original = $this;
        $obj =& $this;

        // The same objects ...(valid)
        echo "<xmp>";
        print_r( $original );
        echo " VS ";
        print_r( $obj );
        echo "</xmp>";

        $tc = new TestQuery();
        $tc->doit( $obj );

        // The same objects newly... (invalid, hoping different) 
        echo "<xmp>";
        print_r( $original );
        echo " VS ";
        print_r( $obj );
        echo "</xmp>";
    }

}

$t = new Test();
$t->num = 2;
$t->exist();

exit;

?>

【问题讨论】:

    标签: php class oop object pass-by-reference


    【解决方案1】:

    我找到的解决方案是使用clone关键字。

    $original = clone $this;
    

    【讨论】:

    • 为了解释:一个对象是PHP总是通过引用分配的。在 java 中也是如此,PHP 只是复制了这种行为。复制对象的唯一方法确实是使用克隆。
    猜你喜欢
    • 2020-07-29
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多