PHP魔术方法__destruct()

2018-09-15 15:00 By "Powerless" 2949 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

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • ACID原则
    Posted on 2020-12-17 16:36
  • 前端知识体系精简-Css
    Posted on 2018-03-28 18:34
  • 浏览器访问网站经历的步骤-Html
    Posted on 2018-11-28 18:48