本文实例讲述了PHP构造函数与析构函数用法。分享给大家供大家参考,具体如下:
在实例化一个新对象时,构造方法和析构方法都会被自动调用,若有继承则会使用父类的对应方法。
析构方法在三种情况下会被调用:
① 使用unset()销毁一个对象,若存在对象传值则不会被调用;
② 改变变量指向对象的值;
③ php程序代码运行结束后。
<?php class base{ public $name; function __construct($name){ $this->name = $name; echo 'obj '.$this->name.' have built'.'</br>'.'</br>'; } function __destruct(){ echo 'obj '.$this->name.' have destroyed'.'</br>'.'</br>'; } } $a = new base('a'); $b = new base('b'); $c = new base('c'); unset($b); $c = 'd';
运行结果如下:
obj a have built obj b have built obj c have built obj b have destroyed obj c have destroyed obj a have destroyed
希望本文所述对大家PHP程序设计有所帮助。