Hi Francisco,
Here's what happens in PHP (the type is checked at runtime, always).
Most programmers understand the basic constructs of Java so I'll
assume you understand them too (PHP basically steals the same ones).
--------------------------------------------------------------
interface Observer
{
public function notify($message);
}
class MyObserver implements Observer
{
public function notify($message)
{
printf("Message received: %s\n", $message);
}
}
class Observable
{
private $_observers = array();
public function addObserver(Observer $observer)
{
$this->_observers []= $observer;
}
public function imaginaryMethod($arg)
{
foreach ($this->_observers as $observer)
{
$observer->notify($arg);
}
}
}
$instance = new Observable();
$instance->addObserver(new MyObserver());
$instance->imaginaryMethod(42); // Message received: 42
-----------------------------------------------------------------
Now if I drop the "implements" declaration....
--------------------------------------------------------------
class MyObserver
{
// ... Snip ...
$instance = new Observable();
$instance->addObserver(new MyObserver()); //Fatal error: Argument 1
must be of type Observer at line X in file xxx
$instance->imaginaryMethod(42); //Program execution has halted
entirely so this never executes
-----------------------------------------------------------------
It's better than a potentially cryptic "call to undefined method
notify()" when somebody forgets that you should use notify() rather
than receive() or such like. This example is so simple it's
unconvincing though... you need to imagine the larger system with many
different points for message passing.
Of course, if you declare that you're implementing the interface (err,
adopt the protocol) than the parser errors as soon as it realises you
haven't implemented the correct methods.
Like I say, it's always debatable but my main reason for using them is
not so heavily for error checking, it's to provide a point of
reference for developers who wish to write components for a larger
system and need to satisfy a pre-defined API.
Cheers,
Chris
PS: I noticed fast enumeration does work when trying to recreate this
in Objective-J... I guess that's just because JS already uses that
same syntax to iterate over the entire object.