Home > Article > Backend Development > PHP constructor analysis
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 'class a'; } }
b. There is a class in php. Class b inherits class a:
<?php include 'a.php'; class b extends a{ function __construct(){ echo '666666'; //parent::__construct(); } function index(){ echo 'index'; } } $test=new b();
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 'a.php'; class b extends a{ function index(){ echo 'index'; } } $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 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!