Home  >  Article  >  Backend Development  >  What are the characteristics of php constructor

What are the characteristics of php constructor

藏色散人
藏色散人Original
2019-10-11 10:34:042422browse

What are the characteristics of php constructor

What are the characteristics of the php constructor?

Constructor

__construct ([ mixed $args [, $... ]] ) : void

PHP 5 allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time a new object is created, so it is very suitable for doing some initialization work before using the object.

Note: If a constructor is defined in a subclass, the constructor of its parent class will not be called implicitly. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor. If the subclass does not define a constructor, it will be inherited from the parent class like an ordinary class method (if it is not defined as private).

Example 1 Using the new standard constructor

For backward compatibility, if PHP 5 cannot find the __construct() function in the class and does not inherit one from the parent class If so, it will try to find an old-style constructor, which is a function with the same name as the class. So the only time a compatibility issue arises is when a class already has a method named __construct() but it is used for other purposes.

Unlike other methods, PHP will not generate an E_STRICT error message when __construct() is overridden by a method with different parameters than the parent class __construct().

Since PHP 5.3.3, in the namespace, methods with the same name as the class name are no longer used as constructors. This change does not affect classes that are not in the namespace.

Example 2

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of What are the characteristics of php constructor. For more information, please follow other related articles on the PHP Chinese website!

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