-1

Here is a code I am taking from another post: Is what seems like polymorphism in PHP really polymorphism?

class Animal {
    var $name;
    function __construct($name) {
        $this->name = $name;
    }
}

class Dog extends Animal {
    function speak() {
        return "Woof, woof!";
    }
}

class Cat extends Animal {
    function speak() {
        return "Meow...";
    }
}

$animals = array(new Dog('Skip'), new Cat('Snowball'));


foreach($animals as $animal) {
    print $animal->name . " says: " . $animal->speak() . '<br>';
}
Community
  • 1
  • 1

1 Answers1

1

Polymorphism means that the sender of a stimulus does not need to know the receiving instance’s class. The receiving instance can belogin to an arbitrary class.

(Object-Oriented Software Engineering: A Use Case Driven Approach, p.55)

In this case, the sender is the print statement that calls $animal->name and $animal->speak(). The object instance can be of arbitrary class that implements the attribute name and the method speak while the whole thing still works. Thus, by this definition, polymorphism.

Or else, what do you mean by polymorphism? (Different people could have different understanding to the same word)

Koala Yeung
  • 7,475
  • 3
  • 30
  • 50