_initialize() and __construct() functions in php

The difference between _initialize() function and __construct() function in php

The content that this article brings to you is about the difference between the _initialize() function and the __construct() function in php. It has a certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The _initialize() method is executed before any method is executed, of course, it also includes the __construct constructor. That is to say, if there is an _initialize() function, calling any method of the object will cause the _initialize() function to be automatically called, and the __construct() constructor is only called once when the object is created, and has nothing to do with other method calls.

__construct here is a double dash, and the _initialize() function is a single dash

If the parent and child classes have the _initialize() function, the child class covers the parent class. If the child class does not have the parent class, the child class inherits the parent class.

By default, the constructor of the subclass will not automatically call the constructor of the parent class. When calling the _initialize() of the subclass object, it will not cause the _initialize() of the parent class to be automatically called

When actually writing the constructor of the subclass, it is generally necessary to add the active call parent::__construct() of the parent class constructor, otherwise it will cause the subclass object null pointer exception, such as Call to a member function assign() on a non-object.

Therefore, in some system background management or comment functions, the related controller can be extended to the base controller:

Base.php:
Insert picture description here
Article.php

Insert picture description here
In this way, before any method of the Article controller is executed, the _initialize() method in Base.php will be executed to check whether it has been logged in, and there is no need to create an object.

Guess you like

Origin blog.csdn.net/weixin_45557228/article/details/109814370