Home > Article > Backend Development > Sample code sharing about constructor function in php
This article will use examples to explain phpHow to use the constructor
PHP official website definition:
The constructor is in the class A special function, when using new operator to create an instance of a class, the constructor will be called automatically. 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:
<?php class a{ function construct(){ echo 'class a'; } }
b.php has class b classInherits a class:
<?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 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 constructor of the parent class at the same time, you must declare parent::construct();
<?php include 'a.php'; class b extends a{ function index(){ echo 'index'; } }
$test=new b();
At this time, class b does not have its own constructor, then the constructor of the parent class will be executed by default.
The above is the detailed content of Sample code sharing about constructor function in php. For more information, please follow other related articles on the PHP Chinese website!