What is the constructor method of PHP class?

Guanhui
Release: 2023-03-03 09:28:01
Original
2926 people have browsed it

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();
?>
Copy after login

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!

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