Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Class Abstraction and Object Interfaces in PHP?

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);
}
like image 910
Mark Tomlin Avatar asked Jun 10 '10 22:06

Mark Tomlin


1 Answers

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.

like image 145
Richard JP Le Guen Avatar answered Nov 08 '22 00:11

Richard JP Le Guen