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

Detailed introduction to php constructor

怪我咯
Release: 2023-03-13 16:28:02
Original
1463 people have browsed it

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;;
 }
}
Copy after login


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();
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template