Home > Article > Backend Development > 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
<?php class BaseClass { function __construct() { print "In BaseClass constructor\n"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructor\n"; } } class OtherSubClass extends BaseClass { // inherits BaseClass's constructor } // In BaseClass constructor $obj = new BaseClass(); // In BaseClass constructor // In SubClass constructor $obj = new SubClass(); // In BaseClass constructor $obj = new OtherSubClass(); ?>
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
<?php namespace Foo; class Bar { public function Bar() { // treated as constructor in PHP 5.3.0-5.3.2 // treated as regular method as of PHP 5.3.3 } } ?>
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!