data-id=1190000004994154 data-licence=>
原文地址:php设计模式(四):继承
introduction
在php设计模式(二):抽象类和接口以及php设计模式(三):封装中,我们已经见过继承,也就是extends关键字。
和c/c++,java,python等语言一样,php也支持继承,而且和其他语言没有什么区别。
继承/inheritance
还是用动物、鲸鱼和鲤鱼来举例:
name . is chewing . $food . .\n; } protected function digest($food) { echo $this->name . is digesting . $food . .\n; }}class whale extends animal { public function __construct() { $this->name = whale; } public function eat($food) { $this->chew($food); $this->digest($food); }}class carp extends animal { public function __construct() { $this->name = carp; } public function eat($food) { $this->chew($food); $this->digest($food); }}$whale = new whale();$whale->eat(fish);$carp = new carp();$carp->eat(moss);?>
运行一下:
$ php inheritance.phpwhale is chewing fish.whale is digesting fish.carp is chewing moss.carp is digesting moss.
注意$this在animal类、whale类、carp类中的用法。
上面的代码看似常见,实则暗含玄机。对于一个好的程序设计,需要:
类和类之间应该是低耦合的。
继承通常是继承自抽象类,而不是具体类。
通常直接继承抽象类的具体类只有一层,在抽象类中用protected来限定。
summary
合理的继承对于好的程序设计同样是必不可少的,结合abstract和protected,能让你编写出结构清晰的代码。
以上就介绍了php设计模式四:继承,包括了设计模式,php方面的内容,希望对php教程有兴趣的朋友有所帮助。