Home  >  Article  >  Backend Development  >  How to implement construct constructor method in php

How to implement construct constructor method in php

WJ
WJOriginal
2020-06-09 17:07:222743browse

How to implement construct constructor method in php

php object-oriented programming constructor method __construct()

The constructor method in php is the first method automatically called by the object after the object is created. There is a constructor in every class. If it is not explicitly declared, there will be a constructor with no parameters and empty content in the class by default.

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.

The declaration format of the constructor in the class

function __constrct([参数列表]){
  方法体//通常用来对成员属性进行初始化赋值
}

Things to note when declaring the constructor in the class

1. Only one constructor can be declared in the same class because PHP does not support constructor overloading.

2. The constructor method name starts with two underscores __construct()

Now let’s look at an example:

<?php    
class Person{                                                                                       
            
public $name;                   
public $age;                  
public $sex;                                                                                                       
        
public function __construct($name="",$sex="男",$age=27){      //显示声明一个构造方法且带参数            
$this->name=$name;            
$this->sex=$sex;                        
$this->age=$age;        
}        
public function say(){            
 echo "我叫:".$this->name.",性别:".$this->sex.",年龄:".$this->age;       
}                                                                                                  
}?>


Create object $Person1 without any parameters $Person1= new Person();echo $Person1->say();//Output: My name is:, Gender: Male, Age: 27

Create object $Person2 with parameter "Zhang San"

$Person2= new Person("Zhang San");echo $Person2->say();/ /Output: My name is: Zhang San, gender: male, age: 27

Create object $Person3 with three parameters

$Person3= new Person("李思" ,"Male",25);echo $Person3->say();//Output: My name is: Li Si, Gender: Male, Age: 25

Related references: php tutorial

The above is the detailed content of How to implement construct constructor method in php. 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