HomePHP The Get_called_class() Function in PHP 5.3
The Get_called_class() Function in PHP 5.3
In this third part of a series on late static bindings, you will learn how to use the “get_called_class()” function bundled with PHP 5.3 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; keep this in mind when developing your own object-oriented applications.
If you ask a group of developers what’s so exciting about PHP 5.3, it’s very probable they'll tell you that this major upgrade of the language now supports native namespaces and anonymous functions. While these enhancements have been widely commented on and discussed in blogs and forums everywhere, PHP 5.3 also includes a rather overlooked feature called Late Static Bindings (LSB). This powerful tool allows you to easily solve common issues that occur when dealing with hierarchies of classes in a static context.
As with many other facets of PHP, by far the best way to understand how LSB work and why they’re so useful under certain conditions is by example. In the two previous articles of this series I explained how to use this feature to create a simple hierarchy of registry classes. In that particular case, the hierarchy was composed of an abstract parent, which implemented a static Singleton method called “getInstance(),” and a concrete array-based registry that obviously inherited the method in question.
This is Inheritance 101, so what’s the big deal? Well, prior to PHP 5.3, the aforementioned “getInstance()” method always would attempt to return an instance of the parent registry, thus throwing a fatal error because this class was declared abstract. However, thanks to the functionality of LSB, it is possible to implement the method so that it now returns the instance of the class from which it’s has been called. That’s very useful, indeed.
It’s valid to point out that in many cases, LSB is used with the constant __CLASS__ to resolve at run time which class has been referenced by a given method. Nevertheless, PHP 5.3 comes bundled with a whole new function named “get_called_class()” which performs a similar task, therefore simplifying the implementation of certain methods, like the one discussed above.
If you’re interested in learning about this function, in this third installment of the series I’m going to explain how to use it with the registry classes defined in the previous tutorials.
Keep reading to start learning how to put the “get_called_class()” function to work for you!