__initialize () and class constructors in thinkphp __construct ()
There's a lot of talk and usage on the internet about __initialize (), it's always a little bit wrong, so I tested it myself. Share the results with everyone. No, please correct it.
First of all, what I'm going to say is
1, __initialize () is not a function in the PHP class, the constructor of the PHP class is only __construct ().
2, class initialization: If the subclass has its own constructor (__construct ()), then call its own initialization, if not, call the parent class's constructor to do its own initialization.
3, when both the subclass and the parent class have the __construct () function, if you want to call the parent class's __constrcut () at the same time when the subclass is initialized, you can use Parent::__construct () in the subclass.
If we write two classes, as follows:
[PHP]View Plaincopyprint?
- Class action{
- Public function __construct ()
- {
- echo ' Hello Action ';
- }
- }
- Class Indexaction extends action{
- Public function __construct ()
- {
- echo ' Hello indexaction ';
- }
- }
- $test = new Indexaction;
- Output---Hello indexaction
It is obvious that the subclass Indexaction is initialized by invoking its own constructor, so the output is ' Hello Indexaction '.
However, the sub-class is modified to
[PHP]View Plaincopyprint?
- Class Indexaction extends action{
- Public function __initialize ()
- {
- echo ' Hello indexaction ';
- }
- }
Then the output is ' Hello Action '. Because the subclass Indexaction does not have its own constructor.
What if I want to invoke the constructor of the parent class at the same time when I initialize the subclass?
[PHP]View Plaincopyprint?
- Class Indexaction extends action{
- Public function __construct ()
- {
- Parent::__construct ();
- echo ' Hello indexaction ';
- }
- }
This allows two sentences to be output simultaneously.
There is, of course, a way to call a subclass in the parent class.
[PHP]View Plaincopyprint?
- 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 ';
- }
- }
This can also output two sentences at the same time.
The method Hello () in the subclass here is similar to __initialize () in thinkphp.
Therefore, the appearance of __initialize () in thinkphp is only convenient for programmers to avoid frequent use of parent::__construct () when writing subclasses, and to correctly invoke the constructor of the parent class within the framework, so We use __initialize () instead of __construct () when initializing subclasses in thnikphp, and of course you can modify the __initialize () function to your preferred function name by modifying the framework.
__initialize () and class constructors in thinkphp __construct ()