SoFunction
Updated on 2025-03-03

Explanation of php constructor example

PHP official website definition:

Copy the codeThe code is as follows:

A constructor is a special function in a class. When an instance of a class is created using the new operator, the constructor will be called automatically. When the function has the same name as the class, this function becomes a constructor. If a class does not have a constructor, then call the constructor of the base class, and if so, call your own constructor

For example, a class a:
Copy the codeThe code is as follows:

<?php
class a{
 function __construct(){
  echo 'class a';
 }
}

There is a class B inherits class A:
Copy the codeThe code is as follows:

<?php
include '';
class b extends a{
 function __construct(){
  echo '666666';
  //parent::__construct();
 }

 function index(){
  echo 'index';
 }
}
 

$test=new b();
If you write this way, class b has its own constructor. Then when instantiating class b, the constructor will be automatically run. At this time, the constructor of the parent class will not be run by default. If you want to run the parent class constructor at the same time, you must declare parent::__construct();
Copy the codeThe code is as follows:

<?php
include '';
class b extends a{
 function index(){
  echo 'index';
 }
}
 

$test=new b();
At this time, class b does not have its own constructor, so the constructor of the parent class will be executed by default.