UNPKG

manual-php

Version:
57 lines (47 loc) 1.23 kB
# 对象继承 PHP 的对象模型也使用了继承。继承将会影响到类与类,对象与对象之间的关系。比如,当扩展一个类,子类就会继承父类所有公有的和受保护的方法。除非子类覆盖了父类的方法,否则被继承的方法都会保留其原有功能。继承对于功能的设计和抽象是非常有用的,而且对于类似的对象增加新功能就无须重新再写这些公用的功能。 ```php <?php class Foo { /** * Return a string. * * @param void * @return string */ public function method(): string { return 'foo'; } /** * Return a string. * * @param void * @return string */ public function test(): string { return 'test'; } } class Bar extends Foo { /** * Override the parent method. * * @param void * @return string */ public function method(): string { return 'bar'; } } $foo = new Foo(); var_dump($foo->method()); // string(3) "foo" var_dump($foo->test()); // string(4) "test" $bar = new Bar(); var_dump($bar->method()); // string(3) "bar" var_dump($bar->test()); // string(4) "test" ```