Home>Article>Backend Development> How to implement construct constructor method in php
The constructor method in php is the first method automatically called by the object after the object is created. There is a constructor in every class. If it is not explicitly declared, there will be a constructor with no parameters and empty content in the class by default.
The role of the constructor
Usually the constructor is used to perform some useful initialization tasks, such as assigning initial values to member properties when creating an object.
The declaration format of the constructor in the class
function __constrct([参数列表]){ 方法体//通常用来对成员属性进行初始化赋值 }
Things to note when declaring the constructor in the class
1. Only one constructor can be declared in the same class because PHP does not support constructor overloading.
2. The constructor method name starts with two underscores __construct()
Now let’s look at an example:
name=$name; $this->sex=$sex; $this->age=$age; } public function say(){ echo "我叫:".$this->name.",性别:".$this->sex.",年龄:".$this->age; } }?>
Create object $Person1 without any parameters $Person1= new Person();echo $Person1->say();//Output: My name is:, Gender: Male, Age: 27Create object $Person2 with parameter "Zhang San"
$Person2= new Person("Zhang San");echo $Person2->say();/ /Output: My name is: Zhang San, gender: male, age: 27
Create object $Person3 with three parameters
$Person3= new Person("李思" ,"Male",25);echo $Person3->say();//Output: My name is: Li Si, Gender: Male, Age: 25
Related references:php tutorial
The above is the detailed content of How to implement construct constructor method in php. For more information, please follow other related articles on the PHP Chinese website!