Introduction
封装中,我们已经见过继承,也就是extends关键字。
和C/C++,Java,Python等语言一样,PHP也支持继承,而且和其他语言没有什么区别。
继承/Inheritance
还是用动物、鲸鱼和鲤鱼来举例:
<?php
abstractclassAnimal{
protected $name;
protectedfunction chew($food){
echo $this->name ." is chewing ". $food .".\n";
}
protectedfunction digest($food){
echo $this->name ." is digesting ". $food .".\n";
}
}
classWhaleextendsAnimal{
publicfunction __construct(){
$this->name ="Whale";
}
publicfunction eat($food){
$this->chew($food);
$this->digest($food);
}
}
classCarpextendsAnimal{
publicfunction __construct(){
$this->name ="Carp";
}
publicfunction eat($food){
$this->chew($food);
$this->digest($food);
}
}
$whale =newWhale();
$whale->eat("fish");
$carp =newCarp();
$carp->eat("moss");
?>
运行一下:
$ php Inheritance.php
Whale is chewing fish.
Whale is digesting fish.
Carp is chewing moss.
Carp is digesting moss.
注意$this在Animal类、Whale类、Carp类中的用法。
上面的代码看似常见,实则暗含玄机。对于一个好的程序设计,需要:
类和类之间应该是低耦合的。
继承通常是继承自抽象类,而不是具体类。
通常直接继承抽象类的具体类只有一层,在抽象类中用protected来限定。
Summary
合理的继承对于好的程序设计同样是必不可少的,结合abstract和protected,能让你编写出结构清晰的代码。
未经允许不得转载:天宝寺||陈瑞轩 » 从零开始学设计模式(4):继承