Pages

Translate

Thursday, 24 January 2013

Tutorial 4 : implementing an Abstract Class


   In this way you can define a set of object that must all follow the same format,and therefore be inter-operable. Any number of classes can extend the original. The only requirements are that each child class must declare all abstract functions,and that they must declared at the same (or a less restrictive) visibility level. Beyond that,the new class may define as many other methods and properties as you want.

Saved as testing.php

<?php
//Define an abstract class for animals
abstract class animal{
//Declare variables(properties)
public $name;
//Make a constructor to be shared that requires a name
public function __construct($namesake){
$this->name=$namesake;
}
//Declare abstract methods that each animal must implement.
abstract public function makeSound();
abstract public function eat($what);
}

//Define a cat class
class cat extends animal{
public function makeSound(){
echo "Meow\n";
}
public function eat($what){
switch ($what){
case 'kibble':
case 'cat food':
case 'mouse':
case 'bird':
echo "The cat says yum!\n";
break;
case 'grass':
case 'tinsel':
case 'hair':
echo "The cat purrs contentedly.\n";
break;
default:
echo "The cat Raises its head haughtily and walks off .\n";
}
}
}

//Define a cow class
class cow extends animal{
public function makeSound(){
echo"Moooooo!\n";
}
public function eat($what){
switch($what){
case 'grass':
case'hay':
case 'salt':
echo "The cow chews its cud.\n";
break;
default:
echo "The cow walks off ignoring it.\n";
}
}
}

//Declare a cat & a cow.
$my_cat=new cat('Mimi-ow');
$my_cow=new cow('Getrude');

echo'<pre>';

//The cat says:Meow
$my_cat->makeSound();

//The cow says:Moo
$my_cow->makeSound();

//What do they each do when they eat grass?

$my_cat->eat('grass');
$my_cow->eat('grass');

echo '</pre>';
?>

output:

Meow
Moooooo!
The cat purrs contentedly.
The cow chews its cud.

No comments:

Post a Comment