Oliver Nassar

PHP: Abstract classes vs static classes; whats what?

October 07, 2009

In the past I've spent a great deal of time trying to understand the different between PHP5 abstract and static classes/methods. I find out, use the differences on whatever I'm doing, and the forget. No more. I will document my understanding here to help myself, and some day others, out.

Methods (not classes) can be defined as static (eg. not static class Oliver{} but rather static function talk()) in order to call them without going through an instantiated object. From my perspective, it makes code cleaner and less messy by wrapping related functions in a class wrapper instead of defining them globally. It should be noted though, that classes with static methods CAN be instantiated, and those methods can be called either statically (via the :: double colon notation, or via the -> right arrow notation on the instantiated object).

That takes us to abstract classes. Abstract classes CANNOT be instantiated. They can be the parent of a class which can be instantiated, but they themselves cannot be. So for example, if I have two types of users, RegularUser and AdminUser, I could create an abstract class User which defines method signatures (via the abstract keyword) like abstract function login($username, $password){} or I can define static functions which can be called (via the same rules as above). A new User object can never be created directly though.

So what does that mean in terms of real-world usage? Personally, if I don't want a class every to be instantiated, such as a class that has utility functions or string manipulation functions, I will define it as abstract, and define all it's methods to be static. If I have a parent object which should never be instantiated, I'll do the same, but leave the method declarations to the child classes for the most part.

So then when do I use a normal class that happens to have static methods? I haven't really. I'm sure there can be uses for it, but I've never found myself in a situation where I need to access an object's method without the context of the object's instantiation. Maybe it'll come up one day, but as I'm moving closer and closer to a full mvc based coding life style, I have a feeling that I won't find myself in that situation anytime soon.