The PHP manual tells us that, though a class may implement more than one interface, "A class cannot implement two interfaces that share function names, since it would cause ambiguity." Makes perfect sense - until, that is, you realize that PHP interfaces contain no code. They're nothing but definitions. Therefore, there is nothing to be ambiguous.
Interfaces have a single purpose: by using them, functions and methods can require their arguments to implement a certain set of methods. (Actually, they merely require that methods matching certain definitions exist.) Suppose we are writing a graphics library, and we have a set of functions for manipulating and drawing objects that have a color. In that case, we may want to have an interface like the following:
interface DrawableInColor
{
public function getColor();
public function setColor($color);
public function draw($x, $y);
}
But suppose we also want to deal with objects that can be resized. Then we may want an interface like this:
interface DrawableAndResizable
{
public function scaleX($x_factor);
public function scaleY($y_factor);
public function draw($x, $y);
}
So what if we have a classof objects that are colored and resizable? So long as we give the class's methods the appropriate names, the class will be an implementation of both the above interfaces. There is no ambiguity, since there is only one method named "draw." In fact, no class can have two functions by the same name, so there can never be ambiguity in declaring that a class implements two overlapping interfaces. But we can't declare it! To use our class with both sets of functions, we would need to remove the functions' interface requirements entirely. The only other solution is to rename the draw() function of one of the interfaces (to draw2(), let's say) and add a dummy function to our class, like this:
public function draw2($x, $y)
{
$this->draw($x, $y);
}
Both "solutions" are terribly ugly, and although the core developers of PHP insist that it is not an object-oriented language, it should at least allow the OO features of the language to be used as such. The restriction on interfaces severely limits their utility in PHP, and the development team should really consider removing it in future releases.
Leave a Comment
Please: No emoticons or excessive punctuation.Trackback this post | Subscribe to the comments via RSS Feed