Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined.
I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.
One thing to remember is that any given class can “inherit” (technically implement) many interfaces but only one sub-class (be that abstract or not).
Interface is a contract whereas Abstract Class is actually a class. Objects cannot be instantiated in either Interface or Abstract Classes.
PHP interfaces can have constants, but not properties (instance variables). If you don’t need to modify your “property”, you can use a constant instead.
For interfaces also talk about “extending” interfaces and “multiple interface inheritance”
Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature – they cannot define the implementation.
– Abstract classes can have consts, members, method stubs and defined methods, whereas interfaces can only have consts and methods stubs.
– Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
– When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don’t have to be defined.
– A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces. Abstract class can extend another abstract class though.
– A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.
Abstract Class
abstract class Animal { function greeting() { $sound = $this->sound(); // exists in child class by contract return strtoupper($sound); } abstract function sound(); // this is the contract } class Dog extends Animal { function sound() { // concrete implementation is mandatory return "Woof!"; } }
Interface
interface animal { function breath(); function eat(); } Note: the interface’s functions/methods cannot have the details/guts filled in – that is left to the class that uses the interface. Example of a class using an interface: class dog implements animal{ function bark() { echo “yap, yap, yap …”; } /* the interface methods/functions must be implemented (given their ‘guts’) in the class */ function breath() { echo “dog is breathing …”;} function eat() { echo “dog is easting …”;} }