HomePHP Page 3 - A Final Example of Late Static Bindings in PHP 5.3
Putting the BlockLevelElementFactory class into action - PHP
Late Static Bindings (LSB), a powerful feature bundled with PHP 5.3, are much easier to master than you might think. Achieving intimate knowledge of them requires only an average background in working with objects and classes. This article concludes a six-part series that shows you what you can do with LSB.
Definitely, one of the most interesting facets of LSB is that, despite what the name suggests, they can be used in the object scope as well. To demonstrate this, below I wrote a simple script which uses the previous concrete factory to create and render a basic div object using the class' constructor. Look at the following code snippet, please:
// create an instance of the BlockLevel Factory and factory a div element
$blFactory = new BlockLevelFactory('Div');
$div = $blFactory->getElement();
->setContent('This is the content of the div.')
That was easy to code and read, wasn't it? As you can see, in this case the div object has been returned to client code using the factory's "getElement()" method. However, what makes this example especially exciting is that the object in question was created at the instance level, and not in a static context as one might expect.
What's more, if you're interested in seeing how this approach can be used for spawning a paragraph object instead of a div, here's how it can be done in a few simple steps:
// create an instance of the BlockLevelElementFactory and factory a paragraph element
$blFactory = new BlockLevelElementFactory('Paragraph');
$par = $blFactory->getElement();
->setContent('This is the content of the paragraph.')
Since this example looks pretty similar to the one that creates a div object, I'm not going waste your time explaining its underlying logic. Instead, it's time to show how to use the previous factory class for spawning the same (X)HTML objects that you saw before, but this time by using its static "create()" method directly.
The full details of this process will be covered in the last section, so click on the link below and read the lines to come.