In keeping with the concepts deployed before, below I coded a script very similar to the one shown in earlier parts of the series, which proves that the functionality of the previous registry classes remains the same, even though some methods have been modified or removed. Look at the following code snippet, please:
// grab the Singleton instance of the autoloader
$autoloader = Autoloader::getInstance();
// grab the Singleton instance of the ArrayRegistry class
$arrayRegistry = ArrayRegistry::getInstance();
// save some users to the registry
$arrayRegistry->set('user1', 'Julie Smith')->set('user2', 'Mary Wilson');
// get the first user from the registry
displays the following
catch (Exception $e)
Well, if you take the time to test the above script on your own web server, it should work like a charm. What’s more, I encourage you to derive a few additional concrete registries from the abstract parent and use the “getInstance()” method with each of these classes. Provided that you have already installed PHP 5.3.0 (or above) on your machine, in all cases the method should return an instance of the class that has been called from client code.
In summary, late static bindings are a useful feature that allows you to build more efficient hierarchies of classes, and in the appropriate context they can be implemented by using the equivalent “get_called_class()” function. However, don’t overuse them; stick when possible to one of the great commandments of object–oriented programming: “Favor Composition over Inheritance.”
In this third chapter of the series, you learned how to use the “get_called_class()” function bundled with PHP 5.3, which as it name suggests, comes in handy for determining at runtime which class has been called in a static context. In certain situations this function can be used as a replacement for late static bindings, but LSB has a wider range of possible uses, so keep this in mind when developing your own object-oriented applications.
In the next part of the series I’m going to recreate yet another use case where LSB can be applied successfully: the implementation of the abstract factory design pattern. So here’s my final suggestion: don’t miss the upcoming tutorial!
blog comments powered by Disqus