PHP魔术方法__destruct()

2018-09-15 15:00 By "Powerless" 2892 0 2

1) 析构方法的声明格式

function __destruct()
{
    // 方法体
}

注意:析构方法不能带任何参数。


2) 析构方法的用法

一般来说,PHP中析构方法并不是太常用。在类中它是可选的,通常用于在对象销毁之前执行某些清理工作。


下面的例子演示了如何使用析构方法:

<?php
class Person{     
    public $name;         
    public $age;         
    public $sex;         
    public function __construct($name="", $sex="Male", $age=22)
    {   
        $this->name = $name;
        $this->sex  = $sex;
        $this->age  = $age;
    }
    /**
     * say方法
     */
    public function say()
    {
        echo "Name:".$this->name.",Sex:".$this->sex.",Age:".$this->age;
    }   
    /**
     * 定义析构方法
     */
    public function __destruct()
    {
            echo "Well, my name is ".$this->name;
    }
}
$Person = new Person("John");
unset($Person); // 销毁上面创建的$Person对象


以上程序的输出结果为:

Well, my name is John

评 论

View in WeChat

Others Discussion

  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56