PHP魔术方法__destruct()

2018-09-15 15:00 By "Powerless" 2796 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 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00
  • 为什么要测量尾部延迟
    Posted on 2020-09-18 10:34