The construction method in PHP is the first method that is automatically called by an object after object creation is complete. There is a construction method in each class, and if it is declared without a display, a constructor with no parameters and empty content is present in the class by default.
The role of the construction method
Typically, a construction method is used to perform some useful initialization tasks, such as assigning an initial value to a member property when creating an object.
The declaration format of a constructor method in a class
function __constrct ([parameter list]) {
Method body//commonly used to initialize member properties to assign values
}
things to notice in declaring a constructor method in a class
1, only one construction method can be declared in the same class, because PHP does not support constructor overloading.
2. The construction method name is the __construct () starting with two bottom lines
Now let's look at an example:
<?PHPclassperson{ Public $name; Public $age; Public $sex; Public function__construct ($name="",$sex= "Male",$age=27) {//Display declares a constructor method with parameters $this->name=$name; $this->sex=$sex; $this->age=$age; } Public functionsay () {Echo"I call:".$this->name. ", Gender:".$this->sex. ", Age:".$this-Age ; } }?>
Create object $person1 without any arguments
$Person 1 New Person (); Echo $Person 1->say (); // output: My name:, Gender: Male, Age:
Create object $person2 with parameter "Zhang San"
$Person 2 New Person ("Zhang San"); Echo $Person 2->say (); // output: My name: Zhang San, gender: Male, Age:
Create an object $person3 with three parameters
$Person 3 New Person ("John Doe", "male", +); Echo $Person 3->say (); // output: My name: John Doe, Gender: Male, Age:
The construction method of PHP object-oriented Programming __construct ()