Explanation of constructor function examples in php

怪我咯
Release: 2023-03-12 19:44:02
Original
1243 people have browsed it

This article will use examples to explain how to use phpconstructor

PHP official website definition:

Constructor It is a special function in the class. When using the new operator to create an instance of the class, the constructor will be automatically called. 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:

The code is as follows:

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

b.php has class b class Inherits 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;;
 }
Copy after login

$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 constructor of the parent class will not be run by default. If you want to To run the parent class constructor, declare parent::construct();

The code is as follows:

<?php
include &#39;a.php&#39;;
class b extends a{
 function index(){
  echo &#39;index&#39;;
 }
}
Copy after login

$test=new b();
At this time, class b has no If it has its own constructor, the constructor of the parent class will be executed by default.

The above is the detailed content of Explanation of constructor function examples in php. 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