Constructor is a special method. It is mainly used to initialize the object when creating the object, that is, assigning initial values to the object member variables. It is always used together with the newoperator in the statement to create the object. A special class can have multiple constructors, which can be distinguished based on the number of parameters or the types of parameters, that is, the overloading of constructors. This article will use examples to explain how to use the php constructor
For example, a.php has a class a class:
The code is as follows:
<?php class a{ function construct(){ echo 'class a'; } }
b.php has class b classInherits 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 you write it like this , class b has its own constructor, then when class b is instantiated, the constructor is automatically run. At this time, the constructor of the parent class is not run by default. If you want to run the constructor of the parent class at the same time, you must 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 does not have its own constructor, so the constructor of the parent class will be executed by default.
The above is the detailed content of Detailed introduction to php constructor. For more information, please follow other related articles on the PHP Chinese website!