Home > Article > Backend Development > The function and usage of PHP object-oriented destructor
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;
The result of the operation is:
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!