PHP Classes and Objects Dynamic Binding

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


Dynamic binding, also referred as method overriding is an example of run time polymorphism that occurs when multiple classes contain different implementations of the same method, but the object that the method will be called on is unknown until run time.

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

class Dog implements Animal {
    public function makeNoise {

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());


In the above example, the Animal class (Dog|Cat) which will makeNoise is unknown until run time depending on the property within the User class.

Got any PHP Question?