Tuesday, February 23, 2010

Object Oriented Programming and Polymorphism in PHP

Introduction:

One of the greatest strengths of any programming language is its Object Orientation and from this comes Polymorphism, way back when I was in college, I studied this section of programming with immense interest and while at first, avenues for its implementation were very limited this is growing day by day.

Following are some examples and implementation of these concepts.

Example:

All Object Oriented Programming languages (OOP languages) offer some form of polymorphism. Following is an example of implementation of polymorphism using PHP:


interface vehicle{
function getType();
function getCapacity();
}

abstract class baseVehicle implements vehicle{
protected type = $type;
}

function getType(){
return ($this->type);
}
}

class motorbike extends baseVehicle{
function getCapacity(){
return ("2 people");
}
}

class car extends baseVehicle{
function getCapacity(){
return ("5 people and 400 litres of boot space");
}
}

class truck extends baseVehicle{
function getCapacity(){
return ("3 people and 10 tonnes of cargo space");
}
}

$vehicleArray = array(
new motorbike("Enfiled Bullet Motorcycle"),
new car("Tata Indigo Station-wagon"),
new truck("Leyland Flatbed Truck")
);

foreach ($vehicleArray as $vehicleData) {
echo $vehicleData->getType() . " - " . $vehicleData->getCapacity() . "\n";
}

Output:

Enfiled Bullet Motorcycle - 2 people
Tata Indigo Station-wagon - 5 people and 400 litres of boot space
Leyland Flatbed Truck - 3 people and 10 tonnes of cargo space

If there are any questions or feedback regarding this, please post in the comments box!