The initialize () and construct () functions in ThinkPHP can be understood as constructor. the previous one is unique to the tp framework, followed by the php constructor, so what are the differences between the two? The initialize () and construct () functions in ThinkPHP can be understood as constructor. the previous one is unique to the tp framework, followed by the php constructor, so what are the differences between the two?
In online search, many answers are the same. initialize in ThinkPHP is equivalent to construct in php. this is wrong. if so, why does tp not use construct, what if we need to get a ThinkPHP version of initialize constructor?
Try it and you will know the differences between the two.
A. php
- Class {
- Function _ construct (){
- Echo 'A ';
- }
- }
Copy the code B. php (note: The constructor does not call parent ::__ construct ();)
- Include 'A. php ';
- Class B extends {
- Function _ construct (){
- Echo 'B ';
- }
- }
-
- $ Test = new B ();
Copy the code running result:
- B
The copied code shows that although Class B inherits Class a, the output shows that the program only executes Class B constructor, but does not automatically execute the constructor of the parent class.
If the constructor of B. php is added with parent :__ construct (), it is different.
- Include 'A. php ';
- Class B extends {
- Function _ construct (){
- Parent: :__ construct ();
- Echo 'B ';
- }
- }
-
- $ Test = new B ();
Copy the code and the output result is:
- AB
The constructor of the parent class is executed only when the code is copied.
Let's take a look at the initialize () function of thinkphp.
BaseAction. class. php
- Class BaseAction extends Action {
- Public function _ initialize (){
- Echo 'baseaction ';
- }
Copy the code IndexAction. class. php
- Class IndexAction extends BaseAction {
- Public function (){
- Echo 'indexaction ';
- }
Copy the code and run the Index method under index. the output result is as follows:
- BaseActionindexAcition
Copy the code. the _ initialize method of the subclass automatically calls the _ initialize method of the parent class. Construct of php, if you want to call the method of the parent class, you must call parent :__ construct () in the subclass construct display ();
This is the difference between initialize and construct in ThinkPHP.
This article talks about blog originality. For more information, see the source!
Author: Xiaotan blog
Web: http://tanteng.sinaapp.com/2013/04/thinkphp-initialize-construct/