In this short little tutorial I am going to be covering abstract classes within PHP5
(as i understand them, Ive never really been a big fan of OO theory, so if i get something wrong then please do correct me).
As you may recall interfaces do not and cannot define the operational behavior of an object, becasue interfaces are 100% abstracted, but rather they define how you (the developer) is to work with the class.
The way i visualize this is to think that i am entering into an 'agreement' between me and PHP, in other words I have defined a list of methods (rules) in the interface that I (or any other developer) must implement in any implemented class, so in any implemented classes i am agreeing to conform with the interface's rules. get me?
Abstract classes are a bit different, an abstract class is a partially abstracted class and can contain functioning methods and also abstracted methods that any class that inherits from it must implement.
confused? don't be, an abstract class merely exists to be extended (inherited) and contains methods and variables common to all derived sub-classes and therefore cannot be directly instantiated.
Now hopefully I've explained the differences, if not, this maybe useful to you, with an interface the creator is saying "Implemented class must implement X, Y, Z as defined in the Interface" where as an abstract he could say "extended class of abstract inherits X but must implement Y, Z as defined in abstract"
Right with the boring stuff out of the way, heres an example i will use from my last article, a DB class but in this case i want to have a common method for all of my objects that inherit the abstract, in this case its an error logging method (I haven't bothered making it a working example, but you should be able to alter to your needs):
Im not going to explain most of the class because I have commented it and since this is an advanced tutorial you should be able to decipher it xD.
Anyway if we try to instantiate DB_Abstract,
Fatal error: Cannot instantiate abstract class DB_Abstract
So we must instantiate the derived object (should have been obvious but just incase anyone didnt see it)
DB_mysql, but in the abstract we defined
connect()as abstract so PHP will want an implementation of it within the inherited object, which in this case we do, but if i was to comment out
DB_mysql, PHP will produce:
Fatal error: Class DB_mysql contains 1 abstract method and must therefore be declared abstract or implement the remaining methods.
I hope that made it clear, like i said, I've never been a guy that likes Object Oriented Theory, in fact it bores me to suicide sometimes so if there is something erroneous here then don't hesitate to shout at me