HomePHP Page 3 - Using Late Static Bindings in PHP 5.3
Attempting to grab an instance of an abstract registry class - PHP
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.
Unless you perform smart unit tests with your classes (which is recommended), they may display an unexpected, erroneous behavior under certain conditions. That’s exactly the case with the array-based registry defined in the previous section, even though it seems as if it would work correctly.
To demonstrate this, below I created a simple script which attempts to grab an instance of the registry via its Singleton “getInstance()” method. Check it out:
// include the source classes
// try to grab the Singleton instance of the ArrayRegistry class
$arrayRegistry = ArrayRegistry::getInstance();
/* this is a static method call that attempts to return an instance of the abstract registry, thus throwing the following error:
Cannot instantiate abstract class RegistryAbstract in path/to/AbstractRegistry.php
That was quite a big surprise, eh? Whenever the script calls up the method in question, the PHP engine complains loudly and raises a fatal error stating that the “RegistryAbstract” class is abstract, and therefore it can’t be instantiated, even though the purpose from the very beginning was to create an object from the array registry. Well, this happened because of the implementation of the “getInstance()” method. This method resolves the called class at compiling time via the keyword “self,” which in this case always returns the abstract parent. Got the point? I hope so.
However, not all is lost with the earlier example, since late static bindings address these and other issues related to static class hierarchies by using the familiar keyword “static.” Naturally, the best way to understand how this feature works is by example, so in the following section I’m going to modify the definitions of the previous registry classes. This time, they’ll work as expected.
To see how this will be done, jump ahead and read the next few lines.