duanfu4446 2013-11-14 18:15
浏览 12
已采纳

PHP是否在分配时复制对象?

Does PHP duplicate an object when = is used or does it just create a new pointer that points to an already existing object?

Are both of these the same?

$obj1 = new object(); 
$obj2 = $obj1;

$obj1 = new object(); 
$obj2 = clone $obj1;
  • 写回答

1条回答 默认 最新

  • dp0518 2013-11-14 18:19
    关注

    In PHP 4 (i.e. ancient history) objects were indeed copied on assignment. This was not helpful behaviour.

    Since PHP 5, objects are now assigned by reference, unless they are cloned.

    You can easily test this:

    $obj1 = new object(); 
    $obj2 = $obj1;
    var_dump($obj1 === $obj2); // bool(true)
    
    $obj1 = new object(); 
    $obj2 = clone $obj1;
    var_dump($obj1 === $obj2); // bool(false)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?