Dynamic Binding
suggest changeDynamic binding, also called method overriding, is runtime polymorphism. Several classes implement the same method, and the object the method is called on is not known until runtime.
This is useful if a certain condition dictates which class will be used to perform an action, where the action is named the same in both classes.
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();
In the example above, the Animal object (Dog or Cat) that runs makeNoise is not known until runtime. It depends on Person::$petPreference. Animal is an interface, not a class.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents