The beginners and even the experts to PHP5 OOP are often confused by interfaces and the practicality of it. It's common to hear, "aren't interfaces just dumbed down abstract classes?" They may be that, but they provide an advantage over abstract classes, besides the "it's the OOP way."
So what makes interfaces so useful? After all, they take more processing power and memory for the PHP engine to use and don't seem to provide any additional functionality.
The answer lies in the fact that you can implement multiple interfaces in the same class. For example, the following is perfectly valid:
PHP Code:
interface Flyable { }
interface Walkable { }
interface Swimable { }
class Goose implements Flyable, Walkable, Swimable { }
It's a pretty basic fact, but it's often overlooked I have found. Remember that interfaces act like a contract. So, if we defined methods in our interfaces (such as fly(), walk(), and swim() respectively), our goose would have to implement all of these methods, or otherwise you get a fatal error.
If you had used abstract classes, you'd do something junky like this: PHP Code:
abstract class Flyable_and_Walkable_and_Swimable { }
class Goose extends Flyable_and_Walkable_and_Swimable { }
This is far from optimal because one of the points of OOP is to re-use code, and here you're just creating every single combination!
Now, if you combine this with type-hinting, you have some sweat code. For example, if you had a fisherman class, you would want the fisherman to only capture things that are swimming. So, you could have:
PHP Code:
class Fisherman implements Walkable
{
public function capture(Swimable $fish) { }
}
You could only pass something to Fisherman::capture() that can swim -- the PHP engine won't let you do otherwise. Type-hinting depends on interfaces, because you can only hint one type. You could not do something like this:
PHP Code:
public function capture(Swimable, Swimable_and_Walkable, Swimable_and_Walkable_and_Flyable $fish) { }
The PHP engine will simply not allow it!
So, interfaces are useful, if you organize your code and think about what needs to happen. They are no longer classes with no implementation, but rather ways to identify.
If you are having trouble on when to use interfaces, I usually think of them as adjectives. Nouns are classes, verbs are methods, adjectives are interfaces.