So, I am starting to gasp the concept of abstract and interface in PHP.
But when is it really ever useful?
Sure I can with an interface make up the rules for my classes, so they all follow a specific pattern. But when is it really useful?
And why should I make an abstract class instead of just making a class that works by it own but is useful for other classes.
Abstract I perhaps can put my head around and see a good use, for example by making a general class. Like making a abstract Database class, then extending it onto a Mysql- and a MsAccess database class. Giving both similar functions to work with, allowing seamless experience in both cases.
But really, could anyone give me a better example of when abstract and interface are really useful?
And please note, I do know how it works, or how to write the code, just not how or when to use it.
Thanks!
An interface is not a class, while an abstract class is already a class.
As every class has an interface (by definition), the
interfaceallows you to specify an interface next to any class, be it abstract or not.Programming against interfaces then allows you to replace one class with another one while keeping the same interface. So it makes your code less coupled. It’s not programmed against concrete classes any longer but “only” against more lightweight interfaces. An interface then is useful if you don’t want to program against concrete class names but against types. You can replace an object then with any other object that implements the same interface.
An abstract class on the other hand – even called abstract – is pretty concrete. However, it’s not final, so it forms a pattern of a class, like a specification how a class that extends from it should be written for a certain functionality. As it’s abstract, it can’t come to live without extending from it. Abstract classes are used to create base classes with code that will be used more than once to reduce code duplication and not being able to instantiate directly.