doulu7921 2014-07-27 19:31
浏览 34
已采纳

如果PHP总是通过引用复制对象,那么如果在方法中创建的对象被分配给成员变量会发生什么?

I'm confused what would happen in this situation:

public function foo() {
    $obj = new \stdClass();
    $obj->bar = 'foobar';

    $this->obj = $obj;
}

If $obj is copied by reference, then when foo() returns, won't $obj be deleted and thus $this->obj point to an object that no longer exists?

  • 写回答

1条回答 默认 最新

  • douyimin1083 2014-07-27 19:42
    关注

    Inside the method this is what it looks like:

    $obj ---------.
                   >-- [OBJECT]
    $this->obj --´
    

    When the method returns the $obj variable is destroyed, and the $this->obj variable will still point to the object:

    $this->obj ------> [OBJECT]
    

    The [OBJECT] value will only disappear (or be garbage collected) once all references to it have been removed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?