DNB5brims
DNB5brims

Reputation: 30568

Where is the object, when I assign a new object to a existing php obj?

For example:

1 $abc = new MyObj();
2 $abc = new MyAnotherObj();

I assign MyObj in the first line, and the second line will assign another object. Where does the object assigned in first line go? Is it still in memory, or somewhere else?

Upvotes: 0

Views: 50

Answers (2)

cdhowie
cdhowie

Reputation: 168988

As soon as the second line executes, the first object will have its destructor called and will be deallocated. PHP's GC does reference counting; when you overwrite the only reference to the MyObj instance, the number of references drops to zero and the GC destroys the object.

Note that this would happen no matter what you assigned to $abc -- you could have assigned "foobar" or 42 or null or even new MyObj() (a new instance of MyObj) and the old object will be destroyed.

See this example on ideone.

Upvotes: 2

kungphu
kungphu

Reputation: 4849

It would be garbage collected in any other language, as there is no longer any reference to it (and you would be unable to reference it further at this point). It's one of those things I just wouldn't do in PHP (or, really, any other language)... if you need a reference to that first object, save it first, or don't use the same variable name.

Upvotes: 1

Related Questions