In this paper, the __initialize () and the constructor __construct () of the class are analyzed 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 PHP class, PHP class constructor only __construct ().
2. Initialization of class: If a subclass has its own constructor (__construct ()), it invokes its own initialization and, if not, invokes the constructor of the parent class for its own initialization.
3, when the subclass and the parent class have the __construct () function, if you want to invoke the __constrcut () of the parent class while initializing the subclass, you can use Parent::__construct () in the subclass.
If we write two classes, as follows:
Copy Code code 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 obvious that initializing a subclass Indexaction calls its own constructor, so the output is ' Hello Indexaction ', but the subclass is modified to:
Copy Code code as follows:
Class Indexaction extends action{
Public Function __initialize ()
{
echo ' Hello Indexaction ';
}
}
So the output is ' Hello Action ' because subclass Indexaction does not have its own constructor, what if I want to invoke the constructor of the parent class while initializing the subclass?
Copy Code code as follows:
Class Indexaction extends action{
Public Function __construct ()
{
Parent::__construct ();
echo ' Hello Indexaction ';
}
}
This allows you to output two sentences at the same time, and of course there is a way to call subclasses in the parent class.
Copy Code code 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 ';
}
}
You can also output two sentences at the same time, and the method in the subclass here, hello () is similar to the __initialize () in thinkphp.
Therefore, the presence of the __initialize () in thinkphp is only convenient for programmers to avoid frequent use of parent::__construct () while writing subclasses, and to correctly invoke the constructor of the parent class within the framework, so When we initialize subclasses in thnikphp, we use __initialize () instead of __construct (), and of course you can modify the __initialize () function by modifying the framework to the name of the letter you like.
I hope this article will be helpful to everyone's thinkphp framework program design.