As I explained in the preceding segment, the “get_called_class()” function included with PHP 5.3 allows you to determine at runtime the class from which a static method has been invoked. To illustrate more clearly how this handy function can be used in a concrete case, below I included the amended versions of the previous registry classes, whose definitions have been slightly shortened thanks to the use of this function. First, this is how the abstract registry class now looks: (RegistryAbstract.php) abstract class RegistryAbstract { protected static $_instances = array();
// get Singleton instance of the registry public static function getInstance() { $class = get_called_class(); if (!isset(self::$_instances[$class])) { self::$_instances[$class] = new $class; } return self::$_instances[$class]; }
// implemented by registry subclasses abstract public function set($key, $value);
// implemented by registry subclasses abstract public function get($key);
// implemented by registry subclasses abstract public function clear(); } And lastly, here’s the definition of the concrete array-based registry: (ArrayRegistry.php) <?php class ArrayRegistry extends RegistryAbstract { private $_data = array();
// save data to the registry public function set($key, $value) { $this->_data[$key] = $value; return $this; }
// get data from the registry public function get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : null; } // clear the registry public function clear() { $this->_data = array(); } } At this point, you’ll have to agree with me that the definitions of the above classes look less cluttered and cleaner, even though the way they work is exactly the same. The most evident improvement is the implementation of the “getInstance()” method defined by the abstract registry, which is considerably shorter thanks to the use of the “get_called_class()” function. Of course, this small enhancement within the method travels down the line of hierarchy, thus making the code of the array registry tighter and more efficient. Having demonstrated how the “get_called_class()” function can simplify the implementation of certain static methods, it’s time to give the previous registry classes a try and see if they still work as expected. This testing process will be accomplished via a final example; to see how this will be done, jump forward and read the section to come.
blog comments powered by Disqus |
|
|
|
|
|
|
|