On Fri, May 17, 2013 at 7:04 AM, Tedd Sperling <tedd.sperl...@gmail.com>wrote:

> To me there is no difference between an abstract class (without method
> declarations) and an interface.

The key difference in OO languages that do not allow multiple inheritance
is that you can always add an interface to an existing class but you can
only mix in an abstract class if your class doesn't extend another.

Let's say you want to define the contract for a UserDataAccessObject with
query and CRUD methods. If you make it an abstract class, I cannot
implement that contract using my AbstractMysqlDao base class. With an
interface, I can do

    class MysqlUserDao
            extends AbstractMysqlDao
            implements UserDataAccessObject

Being a dynamic language, PHP allows you to fulfill a contract without
using interfaces at all. You can call findUserByLogin() on any object--even
those that don't declare that interface via __call(). However, you won't be
able to pass your objects to methods that use parameter type hinting. This
is where interfaces really shine, and they become more important as your
project grows in complexity. They are certainly *not* required to make good
use of OOP, especially in PHP/Python/Ruby.

However, I view an interface as a statement (a contract) where IF you want
> someone to use your code you outline the methods you require them to
> flesh-out in their code  -- but I would like to see a simple example of
> that.

Interfaces come in handy when implementing the visitor and observer
patterns. Simple example are always contrived, but here's mine:

    interface Engine {
        function orderFuel(Store $store);
        function setSpeed($mph);

    class SteamEngine implements Engine {
        function orderFuel(Store $store) {
            $store->order('coal', 1000, WeightUnit::POUND);
        function setSpeed($mph) {
            if ($mph >= 80) {
                throw new InvalidArgumentException('Cannot exceed 80mph');

    class MrFusion implements Engine {
        function orderFuel(Store $store) {
            $store->order('aluminum can');
            $store->order('banana peel');
        function setSpeed($mph) {
            if ($mph >= 88 && empty($this->destinationTime)) {
                throw new IllegalStateException('Must set desired time
travel destination');
            $this->adjustThrottle($mph - $this->speed);

You could make Engine an abstract class, but that would reduce your users'


Reply via email to