Reputation: 21126
If I were to do this:
$bob = new Bob();
function AnnoyBob( Bob $bob )
{
$bob = NULL;
} // < A
AnnoyBob( $bob );
A: Does $bob
now lose its reference to the original pointer and now point to NULL
thus having to get collected on the next GC?
$bob = new Bob();
function AnnoyBob( Bob $bob )
{
unset( $bob );
} // < B
AnnoyBob( $bob );
B: Is the $bob
pointer now instantly releasing the memory for overwriting?
C: What if you were to pass in the reference here instead: ..( Bob &$bob )
My point being, I see people nullifying pointers not realising that they are now leaving GC to do their dirty work... whereas if you use unset, I am wondering if it explicitly marks it to be available for overwriting then and there (deleted)!
Upvotes: 1
Views: 163
Reputation: 522075
You will only ever modify the variable inside the function. Your Bob
instance will continue to exist, because variables outside the function are still referencing it. Bob won't get garbage collected until all references to it are gone/have become inaccessible.
An object instance exists somewhere in a pool of object instances in memory. A variable "holding an object" actually just holds an identifier of that object in memory. If you unset or overwrite that reference, the object itself is not altered. When passing it into a function, you're just passing a copy of the identifier into the function; then see previous sentence.
If you're passing it by reference, then you can modify the caller's variable's content. If you just unset
this variable, it will just unset it inside the function, so nothing much happens to Bob. Only if you pass it by reference and you reassign another value to that variable will Bob get garbage collected.
I.e., only in this scenario are you overwriting the last object reference and cause it to become garbage collected:
$bob = new Bob();
function AnnoyBob(Bob &$bob) {
$bob = NULL;
}
AnnoyBob($bob);
Upvotes: 4