Home >Backend Development >PHP Problem >What is the role of destructor in php

What is the role of destructor in php

王林
王林Original
2020-06-30 11:10:023984browse

The function of the destructor in php is to release memory. The destructor will be called when the object is destroyed. The syntax format for defining a destructor is: [__destruct()]. PHP uses a garbage collection mechanism to automatically clear objects that are no longer used. Even if the unset function is not used, the destructor will be automatically called.

What is the role of destructor in php

Function:

The destructor is called when the object is destroyed, and its function is to release the memory.

The format of defining the destructor is:

__destruct()

Example:

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;

The result of the operation is:

大白对象被销毁了

After the operation is completed, the object is destroyed .

Note:

php uses a "garbage collection" mechanism to automatically clear objects that are no longer used and release memory. That is to say, even if the unset function is not used, the destructor method will automatically called.

If you want to learn more related knowledge, please visit php Chinese website.

The above is the detailed content of What is the role of destructor in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn