Home > Backend Development > PHP Problem > What is the construction method of php?

What is the construction method of php?

烟雨青岚
Release: 2023-03-01 15:10:01
Original
2930 people have browsed it

What is the construction method of php?

#What is the construction method of php?

PHP Constructor __construct() allows the constructor to be executed before instantiating a class.

Constructor method:

The constructor method is a special method in the class. When using the new operator to create an instance of a class, the constructor method will be called automatically, its name must be __construct() .

Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization. Task. This method has no return value.

Syntax:

function __construct(arg1,arg2,...)
{
    ......
}
Copy after login

Example:

<?php
class Person {
    var $name;
    var $age;
    //定义一个构造方法初始化赋值
    function __construct($name,  $age) {
        $this->name=$name;
        $this->age=$age;
    }
    function say() {
        echo "我的名字叫:".$this->name."<br />";
echo "我的年龄是:".$this->age;
    }
}
$p1=new Person("张三", 20);
$p1->say();
?>
Copy after login

Run the example, output:

我的名字叫:张三
的年龄是:20
Copy after login

In In this example, the object properties are initialized and assigned through the constructor method.

*Tips:

PHP will not automatically call the constructor of the parent class in the constructor of this class. To execute the constructor of the parent class, you need to call parent::__construct() in the constructor of the subclass.

Recommended tutorial: "php tutorial"

The above is the detailed content of What is the construction method of php?. For more information, please follow other related articles on the PHP Chinese website!

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