Home  >  Article  >  Backend Development  >  What is the constructor of php? Introduction to the usage of php constructor (example)

What is the constructor of php? Introduction to the usage of php constructor (example)

不言
不言Original
2018-07-24 16:40:206713browse

php constructor is a special method. It is mainly used to initialize the object when creating the object, that is, to assign initial values ​​to the object member variables. It is always used together with the new operator in the statement to create the object. If the description is not clear yet, take a look at the examples I share with you below.

We first create a class and initialize this class.

class Preson{
public $name;                     //定义变量
public $age;
public $sex;
public $height;
}
$Preson1 = new Preson();
$Preson1->$name = "大白";        //变量赋值
$Preson1->$age = 20;
$Preson1->$sex = "女";
$Preson1->$height = 180;

As you can see, the assignment process in the above example is relatively cumbersome. If there are many variables, the workload will be very large and very troublesome. So, we introduced the constructor method. So the function of the constructor is to initialize the object. This method can have no parameters or multiple parameters. Defining a constructor is also very simple, __construct(). It is worth noting that the function construct is preceded by two underscores "_".

After understanding the constructor, we use the constructor to rewrite the above example:

class Preson{
public $name;                     //定义变量
public $age;
public $sex;
public $height;
function __construct($name,$age,$sex,$height){
$this->name = $name;         //为变量赋值
$this->age = $age;
$this->sex = $sex;
$this->height = $height;
}
public function PlayBaskteBall(){
if($this->height>175 || $this->age < 22){
return    $this->name . "可以打篮球";
}else{
return $this->name . "不具备打球的条件";
}
}
}
$Preson1 = new Preson("大白","20","女","180");
echo $$Preson1->PlayBaskteBall(); 		

The constructor is used when initializing the object. If there is no constructor, PHP will automatically generate one. The automatically generated constructor has no parameters and no operations.

Related recommendations:

Detailed explanation of the constructor in php7

The above is the detailed content of What is the constructor of php? Introduction to the usage of php constructor (example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn