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
热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短