Home > Article > Backend Development > Explanation of constructor function examples in php
This article will use examples to explain how to use phpconstructor
PHP official website definition:
Constructor It is a special function in the class. When using the new operator to create an instance of the class, the constructor will be automatically called. When a function has the same name as a class, the function becomes the constructor. If a class does not have a constructor, the constructor of the base class is called. If there is one, its own constructor is called
For example, a.php class a class:
The code is as follows:
<?php class a{ function construct(){ echo 'class a'; } }
b.php has class b class Inherits a class:
The code is as follows:
<?php include 'a.php'; class b extends a{ function construct(){ echo '666666'; //parent::construct(); } function index(){ echo 'index'; }
$test=new b();
If written like this, class b has its own constructor, then when class b is instantiated, 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 To run the parent class constructor, declare parent::construct();
The code is as follows:
<?php include 'a.php'; class b extends a{ function index(){ echo 'index'; } }
$test=new b();
At this time, class b has no If it has its own constructor, the constructor of the parent class will be executed by default.
The above is the detailed content of Explanation of constructor function examples in php. For more information, please follow other related articles on the PHP Chinese website!