Home >Backend Development >PHP Tutorial >Detailed explanation of constructor in php7
When developing with php7, I encountered:
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; index has a deprecated constructor
This prompt is normal and seems easy to understand, and it is found in many articles introducing php7. As mentioned before, this prompt will be thrown when the function with the same name as the class in php7 is used as the constructor . It is recommended to use construct as the constructor. Codes such as ecshop There are many situations where a function with the same name as a class is used as a constructor.
But I found that thinkphp's controller still has the index method in the index controller, and I didn't find that this prompt would be thrown when I used it.
So I went through the code, but from the data and tests, I found that there are several situations:
1. If there are both construct (non-parent class) and a function with the same name as the class name in a class , then construct is a constructor, and the function with the same name is treated as an ordinary function;
2. If the parent class of a subclass has construct (even if it is public) but the subclass does not, and the subclass has function with the same name, and the function with the same name is the constructor. If you use get_class_methods($this); to get the method of the class, you will find that there is actually a construct method;
3. There is this sentence in the official manual of php:
Since PHP 5.3.3 From now on, in the namespace, the method with the same name as the class name will no longer be used as a constructor. This change does not affect classes that are not in the namespace
When testing some conjectures, namespaces are generally not used. Looking at the source code of thinkphp, there is no special treatment anywhere, and it always stays in the first two situations. , very puzzled.
Fortunately, I found the third situation in the official PHP manual, and finally understood why there is no such prompt in thinkphp, because thinkphp uses namespaces.
The above is the detailed content of Detailed explanation of constructor in php7. For more information, please follow other related articles on the PHP Chinese website!