PHPDestructor is the opposite of Constructor. They are called to destroy an object from memory, helping us release the memory occupied by the object properties and destroy the object related H.
The PHP constructor is the first automatically called method after the object is created, and the destructor is the last automatically called method before the object is released. This article introduces you to the PHP constructor and destructor.
php constructor
1. It is the "first" "automatically called" method after the object is created
2.Constructor method The definition of , the method name is fixed,
In php4: the method with the same name as the class is the constructor method
In php5: the constructor method selection uses magic Method construct() Use this name to declare constructors in all classes
Advantages: When changing the class name, the constructor does not need to change
Magic method: When a certain magic method is written in a class, the function corresponding to this method will be added.
The method names are all fixed (all provided by the system), and there is no self-defined
Each magic method, They are all methods that are automatically called at different times to complete a certain function
Different magic methods have different calling timings
They are all methods starting with
construct(); destruct(); set(); ......
Function: Initialize member attributes;
php destructor
1. When the object is released before the last The "automatic" calling method
uses the garbage collector (java php), while c++ manual release
Function: close some resources and do some cleanup work
destruct();
php constructor and destructor examples
class Person{ var $name; var $age; var $sex; //php4中的构造方法 /*function Person() { //每声明一个对象都会调用 echo "1111111111111111"; }*/ //php5中的构造方法 function construct($name,$age,$sex){ $this->name=$name; $this->age=$age; $this->sex=$sex; } function say(){ //$this->name;//对象中成员的访问使用$this echo "我的名字:{$this->name},我的年龄:{$this->age}<br>" } function run(){ } function eat(){ } //析构方法 function destruct(){ } } $p1=new Person("zhangsan",25,"男"); $p2=new Person; $p3=new Person;
The above is the detailed content of Examples of php constructors and destructors. For more information, please follow other related articles on the PHP Chinese website!