Home > Backend Development > PHP Tutorial > Detailed explanation of the __construct() construction method in PHP

Detailed explanation of the __construct() construction method in PHP

autoload
Release: 2023-04-09 21:50:02
Original
3759 people have browsed it

Detailed explanation of the __construct() construction method in PHP

The construction method __construct() is a special method unique to the class structure. This method is specified by the system. The developer can When defining, you only need to write it once. After the class with constructor instantiates the object , the object will be automatically called. This article will take you through it. Take a look.

1. The difference between the construction method and the ordinary method The difference is that Construction method will be automatically called immediately when the object is obtained through class instantiation, while ordinary methods need to be called manually.

2. If the construction method has parameters

<?php
class People{
    public $name;
    private $sex;
    protected $height;

    public function __construct(){
        echo "Knowledge is power!";
    }
    
    public function Hello(){
        echo "你好,世界!";
    }
}
//new People;        两者差别在于是否有参数
$man =new People();//构造方法自动调用
echo "<br>";
$man->Hello();//普通方法手动调用
Copy after login
输出:Knowledge is power!
      你好,世界!
Copy after login

Recommended: 2021 PHP Interview Questions Summary (Collection)》《

php video tutorial

The above is the detailed content of Detailed explanation of the __construct() construction 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