Home  >  Article  >  Backend Development  >  Sample code sharing about constructor function in php

Sample code sharing about constructor function in php

黄舟
黄舟Original
2017-07-02 09:41:411366browse

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


b.php has class b classInherits a class:

<?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 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 &#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, 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!

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