//---------------------OBJECT ORIENTED PROGRAMMING--------------------//
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() . '
';
}
//---------------------PROCEDURAL PROGRAMMING--------------------//
function Animal($name,$speak)
{
return $name . " says: " . $speak;;
}
$animals2 = array('Skip', 'Snowball');
$speak = array('Woof, woof!','Meow...');
for ($n=0;$n';
}
-----------------------------------------------------------------
Question 1: Which code is shorter?
Answer: Procedural
Question 2: Which code is easier to read?
Answer: Procedural
Question 3: How many lines would you need to edit for each to add a pig animal?
Answer (OOP): Add entire new class under Animal (4 lines), add 2 elements to $animals array with new class declarations.
Answer (Procedural): Add 1 new element to $animals2 and $speak arrays. (Oh no, GASP! I used TWO arrays, I'm misusing memory! Except we're not living in 1982 anymore...)
Question 4: So why use OOP?
Answer: To stroke your ego.