Home > Article > Backend Development > What is the construction method of php?
#What is the construction method of php?
PHP Constructor __construct() allows the constructor to be executed before instantiating a class.
Constructor method:
The constructor method is a special method in the class. When using the new operator to create an instance of a class, the constructor method will be called automatically, its name must be __construct() .
Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization. Task. This method has no return value.
Syntax:
function __construct(arg1,arg2,...) { ...... }
Example:
<?php class Person { var $name; var $age; //定义一个构造方法初始化赋值 function __construct($name, $age) { $this->name=$name; $this->age=$age; } function say() { echo "我的名字叫:".$this->name."<br />"; echo "我的年龄是:".$this->age; } } $p1=new Person("张三", 20); $p1->say(); ?>
Run the example, output:
我的名字叫:张三 的年龄是:20
In In this example, the object properties are initialized and assigned through the constructor method.
*Tips:
PHP will not automatically call the constructor of the parent class in the constructor of this class. To execute the constructor of the parent class, you need to call parent::__construct() in the constructor of the subclass.
Recommended tutorial: "php tutorial"
The above is the detailed content of What is the construction method of php?. For more information, please follow other related articles on the PHP Chinese website!