PHP constructor example to explain _php skills

Source: Internet
Author: User
Tags php website

PHP website Definition:

Copy Code code as follows:

A constructor is a special function in a class that is automatically invoked when an instance of a class is created with the new operator. This function becomes a constructor when the function has the same name as the class. If a class has no constructors, call the constructor of the base class, and if so, call its own constructor

such as a.php a Class A:
Copy Code code as follows:

<?php
Class a{
function __construct () {
echo ' Class A ';
}
}

B.php has Class B inherits Class A:
Copy Code code as follows:

<?php
Include ' a.php ';
Class B extends a{
function __construct () {
Echo ' 666666 ';
Parent::__construct ();
}

function index () {
echo ' index ';
}
}

$test =new B ();
In this case, B class has its own constructor, then instantiate Class B, automatically run the constructor, at this time the default does not run the constructor of the parent class, if you want to run the parent constructor, to declare parent::__construct ();
Copy Code code as follows:

<?php
Include ' a.php ';
Class B extends a{
function index () {
echo ' index ';
}
}

$test =new B ();
When 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.