Home >Backend Development >PHP Problem >What is the constructor method of PHP class?

What is the constructor method of PHP class?

Guanhui
GuanhuiOriginal
2020-07-24 14:50:582960browse

What is the constructor method of PHP class?

What is the constructor method of PHP class?

The constructor of the PHP class refers to "__construct()". The constructor is a special method in the class. When the "new" operator is used to create an instance of the class, the constructor will It is called automatically, so it is usually used to perform some useful initialization tasks. This method has no return value.

Example

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

class OtherSubClass extends BaseClass {
    // inherits BaseClass&#39;s constructor
}

// In BaseClass constructor
$obj = new BaseClass();

// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();

// In BaseClass constructor
$obj = new OtherSubClass();
?>

Recommended tutorial: "PHP"

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