Home >Backend Development >PHP Tutorial >Detailed introduction to php constructor

Detailed introduction to php constructor

怪我咯
怪我咯Original
2017-07-12 10:05:561455browse

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 &#39;class a&#39;;
 }
}


b.php has class b classInherits a class:

The code is as follows:

<?php
include &#39;a.php&#39;;
class b extends a{
 function construct(){
  echo &#39;666666&#39;;
  //parent::construct();
 }

 function index(){
  echo &#39;index&#39;;
 }
}
 

$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 &#39;a.php&#39;;
class b extends a{
 function index(){
  echo &#39;index&#39;;
 }
}
 
$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!

Statement:
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