PHP object extends


PHP class inheritance is the establishment of a new derived class, from one or more previously defined class inheritance data and methods, and can be re-defined or added to the new data and methods, thus creating a class hierarchy or level.

We call the existing class that is used to derive the new class as the parent class, and the new class derived from the existing class as the subclass. Inheritance is one of the three characteristics of object-oriented.

Through the inheritance mechanism, you can use the existing data types to define new data types. The new data type defined has not only the newly defined members, but also the old members.

Note: Unlike Java and other languages, in PHP, a class can only directly from a class to inherit data, that is, single inheritance.

Use the extends keyword to define class inheritance:

class subclass extends parent class {
}

example:

class Person {
    var $name;
    var $age;

    function say() {
        echo "My name is: ". $this->name. "<br />";
        echo "My age is: ". $this->age;
    }
}

// Inheritance of classes
class Student extends Person {
    var $school; // Student's school where the property

    function study() {
        echo "My name is: ". $this->name. "<br />";
        echo "I am in the ". $this->school. "learning";
    }
}

$t1 = new Student();
$t1->name = "Joe Smith";
$t1->school = "People's University";
$t1->study();

Run the example and output:

My name is: David
I am studying at Renmin University

In software development, the inheritance of the class makes the established software open, scalable, which is the information organization and classification of the effective method, which simplifies the object, class creation workload, an increase of the code Reproducibility. Inheritance is used to provide a hierarchical structure of classes. Through the inheritance relationship of the class, make the common characteristic can share, have improved the reusability of the software.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook