_ Initialize () and constructor _ construct () in thinkphp ()
There are a lot of comments and usage about _ initialize () on the Internet, which are not correct, so I tested it myself. Share the results with you. Correct the error.
First, I want to talk about
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
Copy code
Obviously, when initializing the subclass indexaction, it will call its own constructor, so the output is 'Hello indexaction '.
But modify the subclass
- Class indexaction extends action {
- Public Function _ initialize ()
- {
- Echo 'Hello indexaction ';
- }
- }
Copy code
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 ';
- }
- }
Copy code
In this way, two sentences can be output at the same time.
Of course, there is also a 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 indexaction extends action {
- Public Function Hello ()
- {
- Echo 'Hello indexaction ';
- }
- }
Copy code
In this way, two sentences can be output at the same time.
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 name by modifying the framework.
Http://www.thinkphp.cn/code/367.html