What is the role of constructor in php

王林
Release: 2023-03-01 18:42:01
Original
3456 people have browsed it

The function of the constructor in php is to initialize the object when creating it, that is, to assign initial values ​​to the object member variables. Constructors are always used with the new operator in statements that create objects. A class can have multiple constructors.

What is the role of constructor in php

Constructor function

The constructor is a special method, mainly used to initialize the object when creating the object, that is, the object member variable Assign initial value. It is always used with the new operator in statements that create objects. A class can have multiple constructors, which can be distinguished based on the number of parameters or the types of parameters, that is, the overloading of constructors.

Example:

We first create a class and initialize this class.

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();
Copy after login

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.

If you want to learn more related knowledge, please visit php Chinese website.

The above is the detailed content of What is the role of constructor in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template