PHP 5.3 introduced a number of valuable features to the popular and constantly developing language, but some of them seem less useful at first glance than they actually are. Late static bindings fall into this category. This article series shows you how to unlock the true power of LSB to work for you.
Without a doubt, PHP is in steady and constant evolution. Its dynamic nature is one of the most relevant factors that has contributed to turning it into the mature language that we see nowadays. This doesn’t mean that its API is a beautiful model of consistence and efficiency, though, especially when compared to older and more solid contenders like C++ and Java.
It’s fair to say, however, that each major release of PHP has been packed with handy features that have made developers’ lives considerably easier (and happier, at least in my personal case). A recent example of this was the introduction a few months ago of PHP 5.3.0. It includes some brand new and exciting characteristics, such as native namespaces, anonymous functions and late static bindings (LSB), aimed at filling some gaps that existed in the language’s API.
The benefits of using namespaces are quite obvious, as they prevent class names from clashing in an elegant and effective fashion. Needless to say, anonymous functions (AKA closures) allow developers to do all sorts of clever things in the code, such as use functions as callback parameters, or even assign a complex function to a single variable (if you've worked with JavaScript since the old pre-jQuery days, you know what I’m talking about here).
But what’s special about late static bindings? At first sight, it seems that LSB offers nothing or little of importance, as it only permits you to determine at run time what class has been called in a static context.
However, this is a misleading impression, trust me. In reality, LSB is a feature so powerful that it makes the upgrade to PHP 5.3 worthwhile all by itself. Let me elaborate on this concept a bit further with a simple example: say that you’ve created a base class which defines a static Singleton method that returns the corresponding instance by referencing the class with the keyword “self” or the constant __CLASS__ . This is fine, as long as you don’t need to extend the class in question and call the method from one of multiple subclasses. If you do so prior to PHP 5.3, you’ll always get an instance of the parent, not of the child classes, since a static call to “self” or __CLASS will be resolved at compiling time.
Fortunately, LSB addresses this issue by determining which class has been referenced in a static context at runtime. Of course, the theoretical side of this feature needs to be backed up with functional code. Given that, in the lines to come I’m going to create some approachable examples that hopefully will help you understand how to put LSB to work for you.