Php Basics: Class and object (3) constructor and Destructor. Constructor PHP5 allows developers to define a method in a class as constructor. Classes with constructors call this method each time an object is created, so it is very suitable for using constructors.
PHP 5 allows developers to define a method in a class as a constructor. Classes with constructors call this method each time an object is created, so it is very suitable for initialization before using the object.
Note:
If the constructor is defined in the subclass, the constructor of its parent class will not be called secretly. To execute the constructor of the parent class, you must call parent ::__ construct () in the constructor of the subclass (). (?? Obviously different from other languages ??)
Example 10. 8. use the new standard constructor
Class BaseClass {
Function _ construct (){
Print "In BaseClass constructor \ n ";
}
}
Class SubClass extends BaseClass {
Function _ construct (){
Parent: :__ construct ();
Print "In SubClass constructor \ n ";
}
}
$ Obj = new BaseClass ();
$ Obj = new SubClass ();
To achieve backward compatibility, if PHP 5 cannot find the _ construct () function in the class, it will try to find the old constructor, that is, the function with the same name as the class. Therefore, the only situation that causes compatibility problems is that the class already has a method named _ construct (), but it is not a constructor.
Destructor
PHP 5 introduces the concept of destructor, which is similar to other object-oriented languages, such as C ++. The Destructor is executed when all references to an object are deleted or when the object is explicitly destroyed.
Example 10. 9. destructor example
Class MyDestructableClass {
Function _ construct (){
Print "In constructor \ n ";
$ This-> name = "MyDestructableClass ";
}
Function _ destruct (){
Print "Destroying". $ this-> name. "\ n ";
}
}
$ Obj = new MyDestructableClass ();
Like constructors, the parent class's destructor will not be called by the engine. To execute the destructor of the parent class, you must explicitly call parent ::__ destruct () in the destructor of the subclass (). (?? Obviously different from other languages ??)
Note:
The Destructor is called when the script is disabled. all header information is sent.
Note:
Throwing an exception in the destructor will cause a fatal error.
PHP5 allows developers to define a method in a class as a constructor. Classes with constructors will call this method each time an object is created, so it is very suitable for use...