Home  >  Article  >  Backend Development  >  How to use the constructor method (__construct)?

How to use the constructor method (__construct)?

王林
王林Original
2019-08-22 09:34:553371browse

1. What is a constructor (function)?
The constructor (function) 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.

2. Grammar

function __construct(arg1,arg2,...)
{
    ......
}

3.demo

<?php
/**
 * Created by PhpStorm.
 * User: liudandan
 * Date: 2018/5/13
 * Time: 11:50
 */
class BaseClass {
    function __construct() {
        print "我是构造函数\n";
    }
}

class SubClass extends BaseClass {
    function __construct() {
        parent::__construct();
        print "我是 SubClass 下的构造函数\n";
    }
}

class OtherSubClass extends BaseClass {

}


$obj = new BaseClass();
$obj = new SubClass();
$obj = new OtherSubClass();

The results are as follows:

How to use the constructor method (__construct)?The above article is an understanding of __construct(). I hope it can help beginners, thank you!

If you want to know more about PHP, please visit the PHP Chinese website: PHP Video Tutorial

The above is the detailed content of How to use the constructor method (__construct)?. 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