Home >Backend Development >PHP Problem >What is the construction method of php class
The constructor method of a class in PHP refers to "__construct()". The constructor method is the first method automatically called by the object after the object is created. It is used to complete the initialization of the object; there will be one in each class. If a constructor is not declared, there will be a constructor with no parameter list and empty content in the class.
Recommended: "PHP Video Tutorial"
Construction method of php class
In PHP, the constructor method of a class refers to "__construct()"
The constructor method is the first method automatically called by the object after the object is created, and is used to complete the initialization of the object
There will be a constructor in each class. If it is not declared, there will be a constructor in the class with no parameter list and empty content. If declared, the default constructor will be overridden.
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.
Declaration format of constructor method in class
function __constrct([参数列表]){ 方法体//通常用来对成员属性进行初始化赋值 }
Things to note when declaring constructor method in class
1. Only one constructor can be declared in the same class because PHP does not support constructor overloading.
2. The name of the constructor method starts with two underscores __construct()
Example:Create a class and create a constructor for it. , the code is as follows:
<?php class Website{ public $name, $url, $title; public function __construct($str1, $str2, $str3){ $this -> name = $str1; $this -> url = $str2; $this -> title = $str3; $this -> demo(); } public function demo(){ echo $this -> name.'<br>'; echo $this -> url.'<br>'; echo $this -> title.'<br>'; } } $object = new Website('php中文网','https://www.php.cn/','构造函数'); ?>
Output:
php中文网 https://www.php.cn/ 构造函数
We use $this in the code, which represents the currently called object, and $this can only be used in class methods.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of What is the construction method of php class. For more information, please follow other related articles on the PHP Chinese website!