【问题标题】:__destruct() executed without unset [duplicate]__destruct() 在未设置的情况下执行 [重复]
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      相关资源
      最近更新 更多