Home >Backend Development >PHP Tutorial >Basic knowledge of PHP: classes and objects (3) constructors and destructors_PHP tutorial
Constructor
PHP 5 allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time an object is created, so it is very suitable for doing some initialization work before using the object.
Note:
If a constructor is defined in a subclass, the constructor of its parent class will not be called secretly. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor. (??Obviously different from other languages??)
Example 10.8. Using the new standard constructor
class BaseClass {
function __construct() {
print "In BaseClass constructorn";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructorn";
}
}
$obj = new BaseClass();
$obj = new SubClass();
For backward compatibility, if PHP 5 cannot find __construct in the class () function, it will try to find an old-style constructor, which is a function with the same name as the class. Therefore, the only situation where compatibility issues will arise is if the class already has a method named __construct(), but it is not a constructor.
Destructor
PHP 5 introduced the concept of destructor, which is similar to other object-oriented languages, such as C++. A destructor is executed when all references to an object are removed or when the object is explicitly destroyed.
Example 10.9. Destructor example
class MyDestructableClass {
function __construct() {
print "In constructorn";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
Like the constructor, the destructor of the parent class will not be called secretly by the engine. To execute the parent class's destructor, parent::__destruct() must be explicitly called in the child class's destructor body. (??Obviously different from other languages??)
Note:
The destructor is called when the script is closed, when all header information has been emitted.
Note:
Attempting to throw an exception in the destructor will result in a fatal error.