In this final section of the article I will create another example to demonstrate how to use the “TextHelper” class that you saw before, but this time by calling its method statically. This concluding example has been coded below, so pay close attention to it, please: // convert new lines to '<br>' tags echo TextHelper::newline_br('The shinning ' . "n" . 'is a scary book of Stephen King!'); /*displays the following The shinning <br /> is a scary book of Stephen King! */
// convert new lines to '<p>' tags echo TextHelper::newline_par('The shinning ' . "n" . 'is a scary book of Stephen King!', 'pid', 'pclass'); /* displays the following <p id="pid" class="pclass">The shinning </p><p>is a scary book of Stephen King!</p> */
// convert new lines to '<div>' tags echo TextHelper::newline_div('the shinning ' . "n" . 'is a scary book of Stephen King!', 'divid', 'divclass'); /* displays the following <div id="divid" class="divclass">the shinning <div></div>is a scary book of Stephen King!</div> */
// uppercase sample string echo TextHelper::uppercase_all('The shinning is a scary book of Stephen King!'); /* displays the following THE SHINNING IS A SCARY BOOK OF STEPHEN KING! */
// lowercase sample string echo TextHelper::lowercase_all('The shinning is a scary book of Stephen King!'); /* displays the following the shinning is a scary book of stephen king! */
// uppercase first character in sample string echo TextHelper::uppercase_first('the shinning is a scary book of Stephen King!'); /* displays the following The shinning is a scary book of stephen king! */ That’s not rocket science, right? Despite the simplicity of the previous examples, they do show how to exploit more efficiently the functionality of the “TextHelper” class without having to derive any objects from it. Logically, this concept may vary depending on the context in which a helper class is going to be used. As a rule of thumb, however, the methods of a helper should generally be called statically, to prevent an unnecessary instantiation of the originating class. Finally, feel free to introduce your own improvements to all of the code samples shown in this tutorial, so you can arm yourself with a more solid knowledge of building helper classes in PHP 5. Final thoughts That’s about it for the moment. Over this second episode of the series, I demonstrated with some code samples how to greatly improve the use of the previous “TextHelper” class by calling its methods out of the object scope, in this way preventing its unnecessary instantiation. In the forthcoming article, things will become even more interesting. I’m going to discuss the creation of another helper class, which will come in handy for building dynamically different parts of a URL. So, here’s my final suggestion: don’t miss the next tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|