_ Initialize () and constructor _ construct () in ThinkPHP cannot be used at will, because your module class inherits the upper class, the upper-level class has a defined value. 1. _ initialize () is not a function in the php class, but a constructor of the php class.
_ Initialize () and constructor _ construct () in ThinkPHP ()
_ Construct in thinkphp cannot be used at will, because your module class inherits the upper class and the upper class has a defined level;
1. _ initialize () is not a function in the php class. the constructor of the php class only has _ construct ().
2. class initialization: if a subclass has its own constructor (_ construct (), it calls its own constructor for initialization. if it does not, then, the constructor of the parent class is called for initialization.
3. when both the subclass and the parent class have the _ construct () function, if you want to call the _ constrcut () function of the parent class at the same time when initializing the child class (), you can use parent ::__ construct () in the subclass ().
If we write two classes:
- Class Action {
- Public function _ construct ()
- {
- Echo 'hello action ';
- }
- }
- Class IndexAction extends Action {
- Public function _ construct ()
- {
- Echo 'hello indexaction ';
- }
- }
- $ Test = new IndexAction;
- // Output --- hello IndexAction
Obviously, when initializing the subclass IndexAction, it will call its own constructor. Therefore, the output is 'Hello indexaction', but the subclass is changed:
- Class IndexAction extends Action {
- Public function _ initialize ()
- {
- Echo 'hello indexaction ';
- }
- }
The output is 'Hello action' because the subclass IndexAction does not have its own constructor. what if I want to call the constructor of the parent class at the same time when initializing the subclass?
- Class IndexAction extends Action {
- Public function _ construct ()
- {
- Parent: :__ construct ();
- Echo 'hello indexaction ';
- }
- }
In this way, two sentences can be output at the same time. of course, another method is to call the subclass method in the parent class.
- Class Action {
- Public function _ construct ()
- {
- If (method_exists ($ this, 'Hello '))
- {
- $ This-> hello ();
- }
- Echo 'hello action ';
- }
- }
- Class IndexAction extends Action {
- Public function hello ()
- {
- Echo 'hello indexaction ';
- }
- }
In this way, two sentences can be output at the same time, and the method hello () in the subclass here is similar to _ initialize () in ThinkPHP ().
Therefore, the emergence of _ initialize () in ThinkPHP only facilitates programmers to avoid frequent use of parent ::__ construct () when writing child classes (), at the same time, correctly call the constructor of the parent class in the framework. Therefore, we need to use _ initialize () instead of _ construct () when initializing the subclass in ThnikPHP (), you can also modify the _ initialize () function to your favorite function name by modifying the framework.