views:

128

answers:

3

What is the difference between a Class Abstraction and an Object Interfaces in PHP? I ask because, I don't really see the point to both of them, they both do the same thing! So, what are the advantages of disadvantages using both against one or the other?

Class Abstraction:

abstract class aClass
{
    // Force extending class to define these methods
    abstract public function setVariable($name, $var);
    abstract public function getHtml($template);
}

Object Interface:

interface iClass
{
    // Force impementing class to define these methods
    public function setVariable($name, $var);
    public function getHtml($template);
}
+8  A: 

You can implement multiple interfaces but only extend one class.

Possible:

class MyClass extends MyAbstract implements MyInterface1, MyInterface2, MyInterface3 {  }

Not Possible:

class MyClass extends MyAbstract1, MyAbstract2 implements MyInterface {  }

Additionally, an interface cannot have implementation.

Possible:

abstract class MyClass {
    function doSomething() {
        echo "I can give this method an implementation as this is an abstract class";
    }
}

Not Possible:

interface MyClass {
    function doSomething() {
        echo "I can NOT give this method an implementation as this is an interface";
    }
}

From the Java Glossary:

An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package.

An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.

You should also take a peek at this question - Damien's point about how an interface is a contract is an important one.

LeguRi
Perfectly put! +1
RobertPitt
I think there is an error, your second **Not Possible:** should be `interface MyClass {` not `abstract class MyClass {`.
Mark Tomlin
@Mark Tomlin - You're right! Good call.
LeguRi
+1  A: 

An abstract class can define method implementation, in addition to method definitions. An inferface can only specify the method definition.

Adam Backstrom
@Adam, I do feel that you best summed it up, however @Richard provided the most complete example.
Mark Tomlin
A: 

Multiple interfaces plus your scripts don't run into any parent confusion.

Jarrod