Nate
Nate

Reputation: 28354

If PHP always copies objects by reference, what happens if an object created in a method is assigned to a member variable?

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?

Upvotes: 0

Views: 24

Answers (1)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

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.

Upvotes: 2

Related Questions