Dynamic Binding

suggest change

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
    {
        $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 above example, the Animal class (Dog|Cat) which will makeNoise is unknown until run time depending on the property within the User class.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Classes and objects:
* Dynamic Binding

Table Of Contents
2 Arrays
4 Types
10 Cookies
11 Classes and objects
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR