PHP object-oriented constructor functions and methods

巴扎黑
Release: 2023-03-07 11:18:01
Original
6660 people have browsed it

What is a constructor? What does the constructor do?

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. A special class can have multiple constructors, which can be distinguished based on the number of parameters or parameter types, that is, the overloading of the constructor.

Maybe you still don’t understand the above description clearly, so let’s explain it to you with an example.

Usage example of constructor

We first create a class and initialize the class.

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

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();
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.

The above is the detailed content of PHP object-oriented constructor functions and methods. For more information, please follow other related articles on the PHP Chinese website!

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