Home > Backend Development > PHP Tutorial > php object inheritance

php object inheritance

伊谢尔伦
Release: 2016-11-23 14:14:30
Original
967 people have browsed it

Inheritance is a well-known programming feature, and PHP’s object model also uses inheritance. Inheritance will affect the relationship between classes and objects and objects.

For example, when extending a class, the subclass will inherit all the public and protected methods of the parent class. Unless the subclass overrides the method of the parent class, the inherited method will retain its original functionality.

Inheritance is very useful for functional design and abstraction, and adding new functions to similar objects eliminates the need to rewrite these common functions.

Note:

Unless autoloading is used, a class must be defined before use. If one class extends another, the parent class must be declared before the child class. This rule applies to classes inheriting other classes and interfaces.

Example #1 Inheritance example

class foo
{
    public function printItem($string)
    {
        echo "Foo:".$string.PHP_EOL;
    }
    public function printPHP()
    {
        echo "PHP is great.".PHP_EOL;
    }
}
class bar extends foo
{
    public function printItem($string)
    {
        echo "Bar:".$string.PHP_EOL;
    }
}
$foo = new foo();
$bar = new bar();
$foo -> printItem('baz');
$foo -> printPHP();
$bar -> printItem('baz');
$bar -> printPHP();
Copy after login

Output result:

Foo:baz

PHP is great.

Bar:baz

PHP is great.


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