Destruct function is automatically executed without unset the variable.
<?php
class cars
{
public static $count=0;
public function __construct($type, $year)
{
$this->type= $type;
$this->year= $year;
cars::$count++;
return true;
}
public function __destruct()
{
echo "The " . $this->type . " is being deleted" . "<br>";
cars::$count--;
}
}
$car1= new cars("Toyota Camry", 2014);
$car2= new cars("Nissan Altima", 2012);
$car3= new cars("Honda Accord", 2010);
$car4= new cars("Tesla Model X", 2015);
$car5= new cars("Tesla Model 3", 2016);
echo "The number of objects in the class is " . cars::$count;
echo "<br>";
unset($car4);
echo "The number of objects in the class is " . cars::$count;
?>
result of running this php file in browser is :
The number of objects in the class is 5
The Tesla Model X is being deleted
The number of objects in the class is 4
The Tesla Model 3 is being deleted
The Honda Accord is being deleted
The Nissan Altima is being deleted
The Toyota Camry is being deleted
My question is, why is the __destruct
function being executed on all objects without explicitly calling unset
in the object?