constructor function
PHP 5 allows the developer to define a method as a constructor in a class. Classes with constructors Call this method each time an object is created, making it ideal for doing some initialization work before using the object.
Attention:
If a constructor is defined in a subclass, the constructor for its parent class is not implicitly called. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor of the child class. (?? Distinctly different from other languages??)
Example 10.8: Using 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 ();
For backwards compatibility, if PHP 5 cannot find the __construct () function in the class, it tries to find the old-fashioned constructor, which is the function with the same name as the class. So the only thing that can create a compatibility problem is that there is already a method named __construct () in the class, but it is not a constructor.
Destructors
PHP 5 introduces the concept of destructors, similar to other object-oriented languages such as C + +. Destructors are removed when all references to an object are deleted or executed when an 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 ();
As with constructors, the destructor of the parent class is not called by the engine. To execute a destructor for a parent class, you must explicitly call Parent::__destruct () in the destructor body of the subclass. (?? Distinctly different from other languages??)
Attention:
The destructor is called when the script is closed, at which point all header information is sent.
Attention:
Attempting to throw an exception in a destructor can result in a fatal error.
The above introduces the basic knowledge of PHP: Class and object 3 constructors and destructors, including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.