【发布时间】:2020-01-04 06:46:14
【问题描述】:
Destruct 函数自动执行,无需取消设置变量。
<?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;
?>
在浏览器中运行这个 php 文件的结果是:
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
我的问题是,为什么 __destruct 函数在所有对象上执行而没有在对象中显式调用 unset?
【问题讨论】:
标签: php destructor