PHP Code:class Animal
{
// This is the base animal class, which Cat and Dog derive from
var $name;
function setName($name)
{
$this->name = $name;
}
function makeSound()
{
echo "...\n";
}
}
class Cat extends Animal
{
// Cat inherits $name, setName() and makeSound() from Animal.
function makeSound()
{
// Here we override makeSound()
echo "Meow!\n";
}
}
class Dog extends Animal
{
function makeSound()
{
echo "Woof!\n";
}
}
class Squirrel extends Animal
{
// Since we don't define anything here, Squirrel will just
inherit everything from Animal and leave it at that
}
$a = new Animal;
$c = new Cat;
$d = new Dog;
$s = new Squirrel;
$a->makeSound(); // Outputs "..."
$c->makeSound(); // Outputs "Meow!"
$d->makeSound(); // Outputs "Woof!"
$s->makeSound(); // Outputs "..."
$animals = array($c, $s, $d, $a);
foreach($animals as $animal)
{
$animal->makeSound(); // Outputs "Meow!", "...", "Woof!" and
"..."
}








Bookmarks