曼谷因美食网
您的当前位置:首页php中析构函数的作用是什么

php中析构函数的作用是什么

来源:曼谷因美食网


作用:

在对象被销毁时析构函数被调用,它的作用是释放内存。

定义析构函数的格式为:

__destruct()

举例:

class Preson{
public $name; //定义变量
public $age;
public $sex;
public $height;
function __construct($name,$age,$sex,$height){
$this->name = $name; //为变量赋值
$this->age = $age;
$this->sex = $sex;
$this->height = $height;
}
function __destruct(){
echo "对象被销毁了";
}
}
$Preson1 = new Preson("大白","20","女","180");
echo $Preson1->name;

运行的结果为:

大白对象被销毁了

运行结束后,对象被销毁了。

注意:

php使用的是一种“垃圾回收”机制,自动清除不再使用的对象,释放内存,就是说即使不使用unset函数,析构方法也会自动被调用。

如果您想学习更多相关知识,请访问gxlcms。

显示全文