Patrick St.Onge
Patrick St.Onge

Reputation: 173

unset property in function also affecting passed variable

I have the following code

<?php
$foo[0] = new stdclass();
$foo[0]->foo = 'bar';
$foo[0]->foo2 = 'bar';
destroy_foo($foo);
var_dump ($foo);

function destroy_foo($foo) 
{
    unset($foo[0]->foo);
}
?>

The output is

array(1) { [0]=> object(stdClass)#1 (1) { ["foo2"]=> string(3) "bar" } } 

I would expect $foo[0]->foo to still exist outside the function, but it doesn't. If I remove the properties and just use an array instead, it works. If I change the variable name inside the function, same problem. How can I use properties but make it work as expected?

Upvotes: 0

Views: 52

Answers (2)

Ganesh
Ganesh

Reputation: 162

In PHP Objects will only free their resources and trigger their __destruct method when all references are unsetted. So, to achieve your desire result, you have to assign null insteadof unsetting it.

$foo[0]->foo = null;

Upvotes: 0

user5192753
user5192753

Reputation:

What you see as an error is a PHP behaviour that's "working as expected": see the objects and references official guide.

It's not clear what you want to achieve with your code, but you should try to pass a clone of your object to the function.

Upvotes: 1

Related Questions