Thinkphp Initialize () and construct () both functions can be understood as constructors, the previous one is unique to the TP framework, followed by the PHP constructor, then what is the difference between the two?
In the online search, many of the answers are the same, thinkphp in initialize equivalent to PHP construct, so that is wrong, if so, tp why not construct, And you have to get a thinkphp version of the Initialize constructor?
Try it yourself and know the difference.
a.php
Class a{
function __construct () {
Echo ' a ';
}
}
Copy Code
b.php (Note: Here the constructor does not call Parent::__construct ();)
Include ' a.php ';
Class B extends a{
function __construct () {
Echo ' B ';
}
}
$test =new B ();
Copy Code
Operation Result:
B
Copy Code
As can be seen, although Class B inherits the Class A, the output proves that the program only executes the constructor of Class B and does not automatically execute the constructor of the parent class.
If the b.php constructor is added with Parent::__construct (), it will be different.
Include ' a.php ';
Class B extends a{
function __construct () {
Parent::__construct ();
Echo ' B ';
}
}
$test =new B ();
Copy Code
Then the output is:
Ab
Copy Code
The constructor for the parent class was executed at this time.
Let's take a look at Thinkphp's Initialize () function.
BaseAction.class.php
Class Baseaction extends action{
Public Function _initialize () {
Echo ' baseaction ';
}
Copy Code
IndexAction.class.php
Class Indexaction extends baseaction{
Public Function () {
Echo ' indexaction ';
}
Copy Code
Run the index method under index to output the result:
Baseactionindexacition
Copy Code
Visible, the _initialize method of the subclass automatically calls the parent class's _initialize method. The constructor of PHP construct, if you want to call the method of the parent class, you must display the call Parent::__construct () in the subclass constructor.
This is the difference between initialize and construct in thinkphp.
The difference between initialize and construct in thinkphp