PHP 动态绑定
示例
动态绑定(也称为方法重写)是运行时多态性的一个示例,当多个类包含同一方法的不同实现时发生,但是直到运行时才 知道要调用该方法的对象。
如果某个条件指示将使用哪个类来执行操作,则该操作很有用,其中在两个类中该操作的名称都相同。
interface Animal {
public function makeNoise();
}
class Cat implements Animal {
public function makeNoise
{
$this->meow();
}
...
}
class Dog implements Animal {
public function makeNoise {
$this->bark();
}
...
}
class Person {
const CAT = 'cat';
const DOG = 'dog';
private $petPreference;
private $pet;
public function isCatLover(): bool {
return $this->petPreference == self::CAT;
}
public function isDogLover(): bool {
return $this->petPreference == self::DOG;
}
public function setPet(Animal $pet) {
$this->pet = $pet;
}
public function getPet(): Animal {
return $this->pet;
}
}
if($person->isCatLover()) {
$person->setPet(new Cat());
} else if($person->isDogLover()) {
$person->setPet(new Dog());
}
$person->getPet()->makeNoise();在上面的示例中,取决于类中的属性,直到运行时才知道的Animal类(Dog|Cat)。makeNoiseUser
热门推荐
2 带马的祝福语简短
4 哈尼族祝福语简短
10 巧克力情侣祝福语大全简短
11 新年祝福语大全牛年 简短
12 红包祝福语简短10字
13 新年导员祝福语简短
14 客户开店祝福语简短大气
15 宝宝生日奶奶祝福语简短
16 酒仙网红包祝福语简短
17 简短浪漫的生日祝福语
18 平安果祝福语简短霸气