Php magic methods-constructor and Destructor, php magic constructor. Php magic methods-constructor and Destructor. php magic constructor php has a magical class of methods that are reserved and usually not explicitly called outside, they used php magic methods-constructor and Destructor, and php magic constructor.
Php has a magical class of methods. these methods are reserved and are generally not explicitly called outside. They start with a double underscore, they are called Magic Methods ). Php officially does not recommend defining other methods that start with a double underline.
This section describes the most common magic methods: constructor and Destructor.
1. constructor (_ construct)
void __construct ([ mixed $args [, $... ]] )
Constructor: classes with constructor will call this method every time a new object is created, so it is very suitable for some initialization services before using the object.
Note:
1. clone does not call constructor
2. if the subclass defines the constructor, the constructor of the parent class will not be called implicitly.
3. the constructor of the subclass can be different from the constructor parameter of the parent class.
4. if the subclass does not define the constructor, php will try to find the constructor of the parent class.
5. if no constructor is defined for the parent class, the parent keyword is used to explicitly call the parent class constructor, causing a fatal error.
1
In addition to the constructor of the magic method, php also supports constructor with the same class name, but the priority is lower than that of the magic method:
1
C3();32 }33 34 }35 36 // C1237 new C1();38 39 // C2140 new C2();41 42 // C3243 // C3144 new C3();
After php5.3.3, a method with the same name as the class name is used in the namespace. it is no longer used as a constructor and remains unchanged outside the namespace:
1
Constructors can use all three access control modifiers, such as the Singleton mode:
1
2. destructor (_ destruct)
void __destruct ( void )
Destructor: The Destructor is executed when all references to an object are deleted or the object is displayed and destroyed.
Note:
1. similar to Constructor, the destructor of the parent class is not secretly called by the engine and must explicitly call parent :__ destruct.
2. exit and die cannot prevent the execution of destructor.
3. a fatal error will prevent the execution of the destructor
4. call exit in the destructor to prevent execution of other unexecuted destructor
5. if no destructor is defined for the parent class, use the parent keyword to explicitly call the parent class.Structure AnalysisFunction, causing a fatal error
Php has a magical class of methods, which are reserved and usually not explicitly called outside. they make...