The constructor method in php is "__construct()", which means that the constructor is allowed to be executed before instantiating a class. The constructor is a special method in the class; when using the new operator to create an instance of a class , the constructor will be called automatically, and its name must be "__construct()".
Recommended: "PHP Video Tutorial"
PHP constructor method __construct() allows to instantiate a class The constructor method is executed before.
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 will be automatically called, and 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.
Grammar:
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 this example, output:
My name is: Zhang San
The age is: 20
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 parent class's constructor, you need to call parent::__construct() in the child class's constructor.
The above is the detailed content of What is the constructor method in php. For more information, please follow other related articles on the PHP Chinese website!