Home > Article > PHP Framework > Understand the difference between initialize and construct in ThinkPHP
ThinkPHP’s two functions, initialize() and construct(), can be understood as constructors. The former is unique to the TP framework, and the latter is the PHP constructor. So this What's the difference between the two?
Searching on the Internet, many answers are that the two are the same. The initialize in ThinkPHP is equivalent to the construct of PHP. It is wrong to say that. If so, why does tp not use construct, but make a ThinkPHP version by itself? What about the initialize constructor?
Related learning recommendations: thinkphp
You will know the difference after you try it yourself.
a.php class a{ function __construct(){ echo 'a'; } }
b.php(Note: The constructor here does not call parent::__construct();)
include 'a.php'; class b extends a{ function __construct(){ echo 'b'; } } $test=new b();
Running result:
b
It can be seen that although class b inherits class a, the output results prove that the program only executes the constructor of class b and does not automatically execute the constructor of the parent class.
It will be different if the constructor of b.php is added with parent::__construct()
.
include 'a.php'; class b extends a{ function __construct(){ parent::__construct(); echo 'b'; } } $test=new b();
Then the output result is:
ab
The constructor of the parent class is 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'; } IndexAction.class.php class IndexAction extends BaseAction{ public function (){ echo 'indexAction'; }
Run the index method under Index, the output result is:
baseActionindexAcition
is visible, The _initialize
method of the subclass automatically calls the _initialize method of the parent class. As for PHP's constructor construct, if you want to call the method of the parent class, you must explicitly call it in the subclass constructor parent::__construct();
This is the initialize and construct in ThinkPHP different.
Related recommendations: Programming video course
The above is the detailed content of Understand the difference between initialize and construct in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!