Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn about _ initialize () and Class 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 IndexActionObviously, 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';
}
}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';
}
}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';
}
}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.
Test.rar (324 B download: 79 times)
AD: truly free, domain name + VM + enterprise mailbox = 0 RMB