Class and object-oriented basis (III)

Source: Internet
Author: User

First, inheritance

You can inherit a class and have another member property and method that already exists for the class, which is called the parent class or base class, and the inheriting class is a subclass. The inheritance relationship is implemented through the extends keyword. In layman's terms, there has to be a "root cause" for inheritance, which you may imagine as having a son or daughter, who will get some "things (properties and methods)" from you, so that your "offspring" is holding all of your (root) traits.

Generate a "root" class (parent or base class)
Syntax: Class father{
}


Produce "Descendants" (subclass)
Syntax: class son extends father{
}

The PHP extends class inherits the sample code:

ClassFather{
protected $name;
function __construct ($name) {//constructor
$this->name= $name;
}

function work () {
echo "{$this->name} I am working;
}
function __destruct () {}//destructor
}

ClasssonExtends father{//Inherit parent class
function Play () {
echo "{$this->name} I'm playing a game;
}
}

$my _father=new father ("Papa"); Creating a parent class object
$my _father->work ();

$my _son=new son ("sons");
$my _son->work ();
$my _son->play ();


Parsing: In the parent class father, we define the general properties and methods, and then define the subclasses. You may find that there are no constructors and destructors within subclasses, because subclasses are all methods that inherit the parent class, so you can call $my_son->work (); This is the inheritance of the PHP class. Also note: PHP can not be multi-layered inheritance, such as: Class A extends B extends C, such inheritance in PHP is invalid, only single inheritance in PHP, can not inherit more, need other ways to "implement" multiple inheritance.

Class and object-oriented basis (III)

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.