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);
}
You can implement multiple interfaces but only extend one class.
class MyClass extends MyAbstract implements MyInterface1, MyInterface2, MyInterface3 { }
class MyClass extends MyAbstract1, MyAbstract2 implements MyInterface { }
Additionally, an interface cannot have implementation.
abstract class MyClass {
function doSomething() {
echo "I can give this method an implementation as this is an abstract class";
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With