__destruct()执行时未取消设置

时间:2019-08-31 08:42:12

标签: php destructor

自动执行销毁功能,而无需取消设置变量。

<?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

1 个答案:

答案 0 :(得分:0)

调用析构函数是因为PHP脚本正在终止。参见documentation of destructors

  

在关闭序列期间,析构函数方法将被称为[...],或以任何顺序