February 25th, 2009
Mini How To for PHP Abstract ClassesWarning: extremely nerdy content follows. Object oriented programming is all the rage these days and PHP provides a fairly complete toolkit to be down with OOP (that’s Object Oriented Programming for non nerds). PHP has gained in popularity for this very reason. However, most of us don’t really go very deep into different OOP features like interface classes and abstract classes. We wade in the shallow waters of plain old basic classes, either intimidated by or oblivious to the depths that OOP has to offer. It’s time to get out of the kiddie pool… we’re going deep. Let’s look at “abstract classes.” While they don’t make for great party conversation, they are a powerful tool if used correctly. Let’s create an example. You need a class for users, which might look like this in it’s simplest form.
Simple enough. But what if you need more than one type of user such as sales and customer? You could create two classes, one for each. The downside of that approach is you will have to maintain two different database tables and two classes. That means if any changes have to happen, such as adding in a captcha, it has to happen in more than one place. You would then have to change both classes and both tables. It can get messy. Abstract classes to the rescue! Abstract classes allow you to have a common set of functions shared by all the classes that are extended from it. Now those who know a bit about OOP may ask, “why don’t we just create a normal class and extend it then?” First off, someone could still use the parent “User” class. This can create instability in the system since not all User objects would be created as Customers and Sales objects, but as the parent (Users). While YOU may know what you are doing, a programmer who follows you may end up pulling out hair and calling down curses on your head. With an abstract class we don’t have to worry about that. You can’t create an object using an abstract class. You have to extend the class AND make sure to write a function for any of those abstract function lines we have in the parent class. If we don’t, PHP will throw an error. Here’s an example of a derived class.
And the Customer class:
Now we have two independent classes that share functionality and each have unique functionality. Neat! Let’s look at the pros and cons for abstract classes: Pros
Cons
![]() Abstract classes are great. I recently used something similar to the above example in a simple CRM. If you do it right it really takes the guess work out of what kind of user you are working with.
Post a Comment
|







