【问题标题】:Difference between $a=&$b , $a = $b and $a= clone $b in PHP OOPPHP OOP 中 $a=&$b 、 $a = $b 和 $a= clone $b 之间的区别
【发布时间】:2012-06-26 10:29:57
【问题描述】:

PHP OOP 中的$a = &$b$a = $b$b = clone $a 有什么区别? $a 是一个类的实例。

【问题讨论】:

    标签: php class reference clone copy-initialization


    【解决方案1】:
    // $a is a reference of $b, if $a changes, so does $b.    
    $a = &$b; 
    
    // assign $b to $a, the most basic assign.
    $a = $b; 
    
    // This is for object clone. Assign a copy of object `$b` to `$a`. 
    // Without clone, $a and $b has same object id, which means they are pointing to same object.
    $a = clone $b; 
    

    通过ReferencesObject Cloning查看更多信息。

    【讨论】:

    • 我写的也差不多! +1,尽管我希望您能多解释一下 PHP 引用和克隆。更新:当然你在我发表评论的同时更新了你的答案:D
    • 我不明白 $a = $b; 之间的主要区别是什么和 $a = &$b;如果您查看php.net/manual/en/language.oop5.references.php 此处的第一个示例,它会给出相同的结果
    • @AnonimWd 是的,对于对象,因为使用$a = $b 会让它们指向同一个对象,但是对于其他类型,当你做$a = $b 时,改变$a 的值不会影响$b.
    【解决方案2】:
    // $a has same object id as $b. if u set $b = NULL, $a would be still an object
    $a = $b;
    
    // $a is a link to $b. if u set $b = NULL, $a would also become NULL
    $a = &$b;
    
    // clone $b and store to $a. also __clone method of $b will be executed
    $a = clone $b;
    

    【讨论】:

      【解决方案3】:

      如果你不知道什么是ZVAL结构,什么是refcount,ZVAL结构中的is_ref是关于什么的,请花点时间了解PHP's garbage collection

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        • 2014-12-05
        • 2017-12-24
        • 2019-12-18
        • 2016-01-13
        • 2013-08-08
        相关资源
        最近更新 更多