PHP constructor analysis

不言
Release: 2023-03-31 22:52:02
Original
1703 people have browsed it

This article will use examples to explain how to use the PHP constructor

PHP official website definition:

The constructor is a special function in a class. When using the 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 has a class a class:

<?php
class a{
 function __construct(){
  echo &#39;class a&#39;;
 }
}
Copy after login

b. There is a class in php. Class b inherits class a:

<?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 written like this, class b has its own constructor. Then when class b is instantiated, the constructor will be automatically run. At this time, the parent class will not be run by default. Constructor, if you want to run the parent class constructor 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();
Copy after login

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 entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About the analysis of facade pattern in PHP

Dynamic loading and xml of php and xml Pagination

Use html_entity_decode to implement HTML entity escaping in php

##

The above is the detailed content of PHP constructor analysis. 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