Php object inheritance

Source: Internet
Author: User
Inheriting a well-known programming feature, PHP's object model also uses inheritance. Inheritance will affect the relationship between classes and objects. For example, when a class is extended, the subclass inherits all the public and protected methods of the parent class. Unless the child class overwrites the parent class method, the inherited method retains its original function. Inheriting a well-known programming feature, PHP's object model also uses inheritance. Inheritance will affect the relationship between classes and objects.

For example, when a class is extended, the subclass inherits all the public and protected methods of the parent class. Unless the child class overwrites the parent class method, the inherited method retains its original function.

Inheritance is very useful for the design and abstraction of functions, and there is no need to re-write these common functions when new features are added to similar objects.

Note:

Unless automatic loading is used, a class must be defined before use. If one class extends the other, the parent class must be declared before the subclass. This rule applies to classes that inherit 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 ();

Output result:

Foo: baz

PHP is great.

Bar: baz

PHP is great.

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.