Home >Backend Development >PHP Tutorial >php object inheritance
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();
Output result:
Foo:baz
PHP is great.
Bar:baz
PHP is great.