What is the constructor method in php

藏色散人
Release: 2023-03-03 14:40:01
Original
2195 people have browsed it

The constructor method in php is "__construct()", which means that the constructor is allowed to be executed before instantiating a class. The constructor is a special method in the class; when using the new operator to create an instance of a class , the constructor will be called automatically, and its name must be "__construct()".

What is the constructor method in php

Recommended: "PHP Video Tutorial"

PHP constructor method __construct() allows to instantiate a class The constructor method is executed before.

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 will be automatically called, and 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.

Grammar:

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 this example, output:

My name is: Zhang San

The age is: 20

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 parent class's constructor, you need to call parent::__construct() in the child class's constructor.

The above is the detailed content of What is the constructor method in 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