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

What is the construction method of php class

青灯夜游
青灯夜游Original
2020-11-05 16:35:205029browse

The constructor method of a class in PHP refers to "__construct()". The constructor method is the first method automatically called by the object after the object is created. It is used to complete the initialization of the object; there will be one in each class. If a constructor is not declared, there will be a constructor with no parameter list and empty content in the class.

What is the construction method of php class

Recommended: "PHP Video Tutorial"

Construction method of php class

In PHP, the constructor method of a class refers to "__construct()"

The constructor method is the first method automatically called by the object after the object is created, and is used to complete the initialization of the object

There will be a constructor in each class. If it is not declared, there will be a constructor in the class with no parameter list and empty content. If declared, the default constructor will be overridden.

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.

Declaration format of constructor method in class

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

Things to note when declaring constructor method in class

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

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

Example:Create a class and create a constructor for it. , the code is as follows:

<?php
    class Website{
        public $name, $url, $title;
        public function __construct($str1, $str2, $str3){
            $this -> name  = $str1;
            $this -> url   = $str2;
            $this -> title = $str3;
            $this -> demo();
        }
        public function demo(){
            echo $this -> name.&#39;<br>&#39;;
            echo $this -> url.&#39;<br>&#39;;
            echo $this -> title.&#39;<br>&#39;;
        }
    }

    $object = new Website(&#39;php中文网&#39;,&#39;https://www.php.cn/&#39;,&#39;构造函数&#39;);
?>

Output:

php中文网
https://www.php.cn/
构造函数

We use $this in the code, which represents the currently called object, and $this can only be used in class methods.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of What is the construction method of php class. 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