constructor function
PHP5 can use __construct () in a class to define a constructor, a class with constructors that will call the function every time the object is created, so it is often used to do some initialization work when the object is created.
Class Car {
function __construct () {
Print "constructor is called \ n";
}
}
$car = new car (); The constructor __construct is called automatically when instantiated, and a string is output here
If you define __construct in a subclass, you do not call the parent class's __construct, and if you need to call the parent class's constructor at the same time, you need to use the parent::__construct () explicit call.
Class Car {
function __construct () {
Print "Parent class constructor is called \ n";
}
}
Class Truck extends Car {
function __construct () {
Print "subclass constructor called \ n";
Parent::__construct ();
}
}
$car = new Truck ();
Destructors
Similarly, PHP5 supports destructors, which are defined using __destruct (), which refers to functions that are executed when all references to an object are deleted, or when an object is explicitly destroyed.
Class Car {
function __construct () {
Print "constructor is called \ n";
}
function __destruct () {
The print "destructor is called \ n";
}
}
$car = new car (); constructor is called when instantiated
Echo ' After use, ready to destroy car object \ n ';
Unset ($car); Destructors are called when destroying
When the PHP code is executed, the object is automatically reclaimed and destroyed, so it is generally not necessary to destroy the object explicitly.
PHP Constructors and destructors