The functionality of Late Static Bindings really shines when used in a static context. It’s feasible, however, to use them at the instance level with the same ease and get successful results as well. Logically, the best way to understand this concept is through some functional code, so let me provide you with an example where this feature will be utilized in the object scope. Consider the following class, which is an abstract factory whose concrete subclasses will be responsible for factoring some basic (X)HTML objects: (HtmlElementFactory.php)
<?php
abstract class HtmlElementFactory { private $_element;
// constructor (Late Static Bindings are used at instance level) public function __construct($element = '', array $options = array()) { if ($element !== '') { $this->_element = static::create($element, $options); } }
public function getElement() { return $this->_element; }
// implemented by concrete factory classes public static function create($element, array $options = array()) { throw new HtmlElementFactoryException('This is an abstract factory and it does not create any concrete HTML element.'); } }
( HtmlElementFactoryException.php)
<?php
class HtmlElementFactoryException extends Exception {} That looks quite interesting, doesn’t it? As you can see, the above abstract factory class defines a static “create()” method, which should be implemented by eventual concrete factories to spawn specific (X)HTML objects. Even though this is a typical schema of the factory pattern, it has a small twist that you may already have noticed: yes, the factory’s constructor internally uses LSB to invoke the pertinent “create()” method. Put in a simple way, this implies that all the child factories derived from the previous abstract parent will be able to factor (X)HTML elements either statically via the aforementioned “create()” method, or in the object scope via the constructor. In summary, we get the best of both worlds. If this explanation sounds a little obscure and difficult to grasp, hopefully all of your doubts will vanish when I show you the definition of a concrete factory, which in this case will be tasked with factoring some block-level (X)HTML objects. The definition of this brand new class will be shown in the next section. Thus, go ahead and read the following lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|