This paper analyzes the __initialize () and the constructor __construct () of the class in thinkphp. Share to everyone for your reference. The specific analysis is as follows:
Thinkphp in the __construct is not to be used casually, because your module class inherits the Superior class, the superior class has the definition good;
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:
Copy CodeThe code is as follows: 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 very obvious that when the subclass Indexaction is initialized it calls its own constructor, so the output is ' Hello Indexaction ', but the subclass is modified to:
Copy CodeThe code is as follows: Class Indexaction extends action{
Public Function __initialize ()
{
echo ' Hello Indexaction ';
}
}
So the output is ' Hello Action ' because the subclass Indexaction does not have its own constructor, and if I want to invoke the constructor of the parent class while initializing the subclass?
Copy CodeThe code is as follows: Class Indexaction extends action{
Public Function __construct ()
{
Parent::__construct ();
echo ' Hello Indexaction ';
}
}
This allows two sentences to be output at the same time, and one way is to invoke the subclass's method in the parent class.
Copy CodeThe code is as follows: 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 also allows two sentences to be output simultaneously, and the method hello () in the subclass 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 the name of your favorite functions by modifying the framework.
The Magic method in thinkphp