Пример #1
0
$animal_two = new Dog();
$animal_two->name = "Grover";
$animal_two->favorite_food = "Mushrooms";
$animal_two->sound = "Grrrrrrr";
// Even though we are referring to the Dog $number_of_animals it
// still increases even with subclasses
echo $animal_two->name . " says " . $animal_two->sound . " give me some " . $animal_two->favorite_food . " my id is " . $animal_two->id . " total animals = " . Dog::$number_of_animals . "<br /><br />";
// 2. Because of method overriding we get different results
$animal_one->run();
$animal_two->run();
// 3. final methods can't be overriden
$animal_one->what_is_good();
// 4. Example using __toString()
echo $animal_two;
// 5. You call a method defined in an interface like all others
$animal_two->sing();
// 6. You can also define functions that will except classes
// extending a secific class or interface
function make_them_sing(Singable $singing_animal)
{
    $singing_animal->sing();
}
// 6. Polymorphism states that different classes can have different
// behaviors for the same function. The compiler is smart enough to
// just figure out which function to execute
make_them_sing($animal_one);
make_them_sing($animal_two);
echo "<br />";
function sing_animal(Animal $singing_animal)
{
    $singing_animal->sing();