I’ve been reading a lot about OOP in PHP, and I’ve noticed that these concepts may be confusing since they seem to work the same way.
Interfaces
Interfaces allow you to define methods a class implementing the interface and how to handle them.
All the methods specified in an interface must be implemented in a class.
interface GeometricShape {
public function getArea();
public function draw();
// ...
}
Features of an Interface:
- A class can implement several interfaces.
- Interface constant cannot be overridden.
- Methods cannot contain code/logic.
- Methods must be public.
- Slower than abstract classes
Abstract Classes
Abstract classes look like interfaces but, this abstract classes can define methods, in other words, you can put a “default” logic to the abstract class methods.
abstract class GeometricShape {
abstract protected function getArea() {
// You can add some "default" code here
return 0;
}
}
Features of Abstract Classes
- A class can only extend one abstract class.
- Constrants can be overridden.
- Methods can contain logic (i.e. default code which can be overridden).
- Shared code can be in abstract classes.
- Fast.
There are more features you can find in an interface or an abstract class, however I don’t recall them right now
- http://php.net/manual/en/language.oop5.interfaces.php
- http://www.php.net/manual/en/language.oop5.abstract.php
