Object Oriented PHP: Part 8

Here's the series so far:

Abstraction

Sometimes you need a class, but you don't need to initiate it. In cases like this, you want an abstract class. Take for example, our SalesItem class. Since it has two child classes that we are very likely to use, we don't need direct access to it. Let's make it an abstract class:


class SalesItem {\n
// SalesItem Class...\n
}

As you can see, all we needed to do is add the abstract keyword. Abstract classes define and implement classes, but doesn't instantiate them.

Not only do you have abstract classes, but abstract methods. In our SalesItem class, we could make a new method:


abstract class SalesItem {\n
private $brand;\n
private $name;\n
private $price = 0;\n
\n
protected function __construct( $brand, $name, $price ) {\n
$this -> brand = $brand;\n
$this -> name = $name;\n
$this -> price = $price;\n
}\n
\n
protected function getSummary() {\n
$summary = "{$this -> brand}" . " {$this -> name}";\n
return $summary;\n
}\n
\n
abstract protected function getSummary();\n
}

Remember, any class that extends a class with an abstract method must also implement that method. Abstract methods don't have a body, they are immediately closed with a semicolon.

Interfaces

In addition to abstract classes there are interfaces. Interfaces define objects but don't implement any code. Let's implement an interface:


interface Shippable {\n
protected function getZip();\n
};\n
\n
class BigBox implements Shippable {\n
public function getZip() {\n
return $this -> zip;\n
}\n
}

Note that while a class in PHP can only inherit from one parent class it can implement any number of interfaces, so it would make sense that our LPItem would implement the Shippable interface while the MP3Item wouldn't.

So there you have it, abstract classes and interfaces. Next up, static methods and members.

User login

Contacting Rob

Y! roberthenrylowe
AIM roberthenrylowe
ICQ 249971225
email rhlowe [at] gmail dot com

Networking Links