Php constructor example

Source: Internet
Author: User
This document describes how to use php constructor using examples.

This document describes how to use php constructor using examples.

PHP official website definition:

The Code is as follows:


Constructor is a special function in a class. When you use the new operator to create an instance of a class, the constructor will automatically call it. When the function and the class name are the same, this function will become a constructor. If a class has no constructor, the base class constructor is called. If yes, the base class constructor is called.


For example, a. php class:

The Code is as follows:


Class {
Function _ construct (){
Echo 'class ';
}
}


B. php has a class B class that inherits class:

The Code is as follows:


Include 'a. php ';
Class B extends {
Function _ construct (){
Echo '20140901 ';
// Parent ::__ construct ();
}

Function index (){
Echo 'index ';
}
}


$ Test = new B ();
In this case, Class B has its own constructor. When Class B is instantiated, the constructor is automatically run. By default, the constructor of the parent class is not run, if you want to run the parent class constructor at the same time, declare parent :__ construct ();

The Code is as follows:


Include 'a. php ';
Class B extends {
Function index (){
Echo 'index ';
}
}


$ Test = new B ();
If Class B does not have its own constructor, the constructor of the parent class is executed by default.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.