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 { __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 is called \ n"; Parent::__construct (); }} $car = new Truck ();
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"; } __destruct () { print "destructor is called \ n"; }} $car = new car (); When instantiated, the constructor is called after Echo ' is used, ready to destroy the 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--constructor function and destructor