Assigning new object to a variable causes
__destruct
method to call and the old object gets deleted
(the same result when we run
unset($old_object)
)
class User {
public $username;
public $friends = ['Tom','David'];
function __construct($name) {
$this->username = $name;
print $this->username . "'s object is created'\n";
}
function __destruct() {
print $this->username . "'s object is deleted'\n";
}
}
$user1 = new User('Tom');
$user1 = new User('George');
unset($user1);
$user2 = new User('David');
echo "\n\n";
After executing the above code the result will be the following:
Tom's object is created'
George's object is created'
Tom's object is deleted'
George's object is deleted'
David's object is created'
David's object is deleted'
In this example when George's object gets created, Tom's object gets deleted immediately.
The reason is that we no longer have Tom's object in
$user1
variable