This document describes how to use php constructor using examples.
This document describes how to use php constructor using examples.
PHP official website definition:
The Code is as follows:
Constructor is a special function in a class. When you use the new operator to create an instance of a class, the constructor will automatically call it. When the function and the class name are the same, this function will become a constructor. If a class has no constructor, the base class constructor is called. If yes, the base class constructor is called.
For example, a. php class:
The Code is as follows:
Class {
Function _ construct (){
Echo 'class ';
}
}
B. php has a class B class that inherits class:
The Code is as follows:
Include 'a. php ';
Class B extends {
Function _ construct (){
Echo '20140901 ';
// Parent ::__ construct ();
}
Function index (){
Echo 'index ';
}
}
$ Test = new B ();
In this case, Class B has its own constructor. When Class B is instantiated, the constructor is automatically run. By default, the constructor of the parent class is not run, if you want to run the parent class constructor at the same time, declare parent :__ construct ();
The Code is as follows:
Include 'a. php ';
Class B extends {
Function index (){
Echo 'index ';
}
}
$ Test = new B ();
If Class B does not have its own constructor, the constructor of the parent class is executed by default.