|
Posted by Oli Filth on 11/26/05 14:59
Oliver Saunders said the following on 26/11/2005 03:10:
>> * Adding a constructor to interface definitions - that literally makes
>> no sense at all.
>
>
> I never did really get the point of defining interfaces. Care to
> enlighten me Oli?
Interfaces are a kind of substitute for multiple inheritance.
Whereas traditional inheritance relates classes that are sub-classes
(i.e. more specific instances) of a base class, interfaces allow
otherwise unrelated classes to expose the same specific set of behaviours.
A good example might be an iterator; e.g.:
interface Iterator
{
public function next();
public function previous();
public function rewind();
}
class Kennel implements Iterator
{
private $dogs = array("Rex", "Fido", "Boxer");
// lots of kennel-related functions here
public function next()
{
// return next dog
}
public function previous()
{
// return previous dog
}
public function rewind()
{
// go back to start of dog list
}
}
class DataPacket implements Iterator
{
private $data = "FF:32:5C:39:01:00:A6";
// lots of packet-related functions here
public function next()
{
// return next byte
}
public function previous()
{
// return previous byte
}
public function rewind()
{
// go back to first byte in packet
}
}
Now DataPacket and Kennel objects can both be passed to any function
expecting an Iterator. The same effect could be achieved by defining a
common base class and extending Kennel and DataPacket from that, but
that wouldn't make much sense because they have nothing in common
semantically.
From a practical point of view, if DataPacket and Kennel had been
derived from a common base class, that would put severe limitations on
any other inheritance relationships, e.g. if you had wanted Kennel to be
a sub-class of Building, then you'd be screwed.
--
Oli
Navigation:
[Reply to this message]
|