1 _ initialize () is not a constructor in the php class. The constructor of the php class only has _ construct ().
Class 2 Initialization: If the subclass has its own construct _ construct (), it calls its own 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
The code is as follows: |
Copy code |
Class Action { Public function _ construct (){ Echo 'hello action '; } } Class IndexAcion extends Action { Public function _ construct (){ Echo 'hello, indexaction '; } } $ Test = new IndexAcion (); Output --- hello IndexAction |
Obviously, when initializing the subclass IndexAction, it will call its own constructor, so the output is 'Hello indexaction'
But modify the subclass
The code is as follows: |
Copy code |
Class IndexAcion 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?
The code is as follows: |
Copy code |
Class IndexAcion extends Action { Public function _ construct (){ Parent: :__ construct (); Echo 'hello indexaction '; } } In this way, two sentences can be output simultaneously. Of course, there is another way 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 IndexAcion extends Action { Public function hello (){ Echo 'hello indexaction '; } } |
In this way, two sentences can be output simultaneously.
The method hello () in the subclass 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 by modifying the framework.