Home  >  Article  >  Backend Development  >  Understanding of PHP constructors

Understanding of PHP constructors

巴扎黑
巴扎黑Original
2016-11-23 11:35:471015browse

I encountered some errors while working on the project. In the final analysis, it was the PHP constructor method that caused the problem. Here is a re-arrangement:
Starting with PHP5, you can declare the __construct constructor method in the class. When the object is instantiated, this method is called.
Note:
1. If there is no constructor method in the inherited subclass but there is a constructor method in the parent class, then when the subclass is instantiated, the constructor method of the parent class will be implicitly called.
2. If the subclass has a constructor and the parent class also has a constructor, then the subclass must explicitly call parent::__construct() to access the parent class's constructor.

For backward compatibility, if the __construct() method is not found in the php5 class, it will look for a constructor with the same method name as the class name, but if two constructors are used at the same time, E_STRICT level may occur Error message:
(The following code is my web environment: win32+php5.3.8+apache2.2 test)

Result: Strict Standards: Redefining already defined constructor for class B in D:xampphtdocstest3Class.php on line 8
this is __construct()

But just changing the position of the method is different and the result is different:

In fact, starting from php5.3.3, the method with the same name as the class is no longer used as the constructor of the class, and the same is true for namespace classes. If you are using php5.3.3 or above, you cannot use the method with the same name as the class as the constructor:

If you have to use two constructors at the same time on php5.3.3 or above, then you can do this:


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn