The role of the php constructor method
The role of the php constructor method is to initialize the object when creating it. That is, assigning initial values to object member variables, which are always used together with the new operator in statements that create objects. A special class can have multiple constructors, which can be distinguished based on the number of parameters or parameter types, that is, the overloading of the constructor.
Related recommendations: [PHP Tutorial]
Constructor
__construct ([ mixed $args [, $... ]] ) : void
PHP 5 allows developers to work in a class Define a method as a constructor. 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 implicitly called. 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 also If it does not inherit one from the parent class, 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 } } ?>
The above is the detailed content of The role of php constructor method. For more information, please follow other related articles on the PHP Chinese website!