How to implement construct constructor method in php

WJ
Release: 2023-04-08 20:42:01
Original
2805 people have browsed it

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([参数列表]){
  方法体//通常用来对成员属性进行初始化赋值
}
Copy after login

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;       
}                                                                                                  
}?>
Copy after login


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!

Related labels:
php
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