PHP destructors are the opposite of constructors, and they are called to destroy an object from memory, helping us to free up the memory occupied by the object's properties and destroying the object's associated resources.
The PHP constructor is the first method that is automatically called after the object is created, and the destructor is the last method that is called automatically before the object is freed. This article introduces you to PHP constructors and destructors.
PHP constructors
1. Is the "first" "Auto-call" method after object creation is complete
2. The definition of the construction method, the method name is a fixed,
In PHP4: The same method as the class name is the construction method
In PHP5: The constructor method is chosen using the Magic Method construct () All classes declare the constructor method using this name
Pros: When changing the class name, the construction method does not have to change
Magic method: In the class to write a magic method, the method corresponding to the function will add
The method names are fixed (both are system-provided) and do not have their own defined
Every Magic method is a method that is called automatically at different times in order to complete a function.
Different magic methods have different calling timing
It's all the way to the beginning.
Construct (); Destruct (); Set ();
Function: Initialize the member property;
PHP destructor
1. Method of the last "automatic" call before the object is released
Using the garbage collector (Java PHP), and C + + manual release
Role: Close some resources and do some cleanup work
Destruct ();
PHP Constructors and destructor instances
class person{var $name; var $age; var $sex;//php4 constructor Method/*function person () {//Per declaration An object will call echo "1111111111111111"; The construction method in}*///php5 function construct ($name, $age, $sex) {$this->name= $name; $this->age= $age; $this->sex= $sex;} function say () {//$this access to members of->name;//object using $this echo "My name: {$this->name}, my age: {$this->age}<br>"} function run () {} function Eat () {}//destructor function destruct () {}} $p 1=new person ("Zhangsan", 25, "male"); $p 2=new person; $p 3=new person;