Home > Backend Development > PHP Tutorial > The function and usage of PHP object-oriented destructor

The function and usage of PHP object-oriented destructor

巴扎黑
Release: 2023-03-07 11:20:01
Original
4486 people have browsed it

The previous article explained php object-oriented constructor, this lesson will talk about the corresponding destructor.

The role of the destructor is exactly the opposite of that of the constructor. It is called when the object is destroyed, and its role is to release memory. The format for defining a destructor is: __destruct(), which is the same as the constructor, preceded by two underscores "_".

The role and usage of the destructor

We use an example to deepen the usage of the analytical destructor.

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;
Copy after login

The result of the operation is:

The function and usage of PHP object-oriented destructor

After the operation is completed, the object is destroyed.

Notes on using the destructor:

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 be called automatically. Here we just clarify when the destructor is called. Under normal circumstances, there is no need to manually pass through the piece destruction method.

The above is the detailed content of The function and usage of PHP object-oriented destructor. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template