What is the constructor of it? Constructors what effect?

 

 

Constructor is a special method. Mainly used to initialize the object when you create an object, an object that is assigned an initial value of the member variables, always use the statement to create objects with the new operator. A particular class can have multiple constructors, they can be distinguished i.e. constructor overloads to make different types of parameters or the number of its parameters.

The above description we may still not very clear understanding, we have an example to explain to the next child. Linear motor manufacturer

Examples of the use of a constructor

Let's create a class, and initialize the class.

1

2

3

4

5

6

7

8

9

10

11

class Preson{

public $name;                     //定义变量

public $age;

public $sex;

public $height;

}

$Preson1 = new Preson();

$Preson1->$name = "大白";        //变量赋值

$Preson1->$age = 20;

$Preson1->$sex = "女";

$Preson1->$height = 180;

You can see, the above example the assignment process more complicated, if a lot of variables, then the workload will be very large, very troublesome. So, we introduced a constructor. Therefore, the role of constructor is used to initialize the object. The method may no parameters, there may be a plurality of parameters. The definition of a constructor is very simple, __ construct (), is worth noting that the previous function construct two underscore "_."

Knowing the constructor, we use the constructor to rewrite the above example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

Constructor is used to initialize the object, if there is no constructor, PHP will automatically generate a. Automatically generated constructor no parameters, no operation.

These are the details of an object-oriented function configured php function and methods,

Guess you like

Origin www.cnblogs.com/furuihua/p/12083700.html