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?
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.
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.
精彩评论