The best way to take advantage of the functionality given by the previous text helper class without dealing with its incidental instantiation is declaring its methods static. To do this, I’m going to subtly modify the definition of the class in question, which now will look as follows: class TextHelper { // constructor not implemented public function __construct(){}
// convert new lines to '<br />' tags public static function newline_br($str) { if (is_string($str) AND empty($str) === FALSE) { return nl2br($str); } }
// convert new lines to '<p>' tags in string public static function newline_par($str, $id = '', $class = '') { if (is_string($str) AND empty($str) === FALSE) { if ($id != '') { $id = ' id="' . $id . '"'; } if ($class != '') { $class = ' class="' . $class . '"'; } return '<p' . $id . $class . '>' . str_replace("n", '</p><p>', $str) . '</p>'; } }
// convert new lines to 'div' tags in string (id and class attributes can also be specified) public static function newline_div($str, $id = '', $class = '') { if (is_string($str) AND empty($str) === FALSE) { if ($id != '') { $id = ' id="' . $id . '"'; } if ($class != '') { $class = ' class="' . $class . '"'; } return '<div' . $id . $class . '>' . str_replace("n", '<div></div>', $str) . '</div>'; } }
// uppercase all characters in string public static function uppercase_all($str) { if (is_string($str) AND empty($str) === FALSE) { return strtoupper($str); } }
// lowercase all characters in string public static function lowercase_all($str) { if (is_string($str) AND empty($str) === FALSE) { return strtolower($str); } } // uppercase first character in string public static function uppercase_first($str) { if (is_string($str) AND empty($str) === FALSE) { return ucfirst(strtolower($str)); } } } If you've frequently worked with static methods, then you’ll quickly grasp the modified signature of the text helper class. Most of its source code remains practically the same, except for the static declaration of all of its methods (apart from the constructor). Even though this modification seems to be insignificant at first sight, it introduces a great enhancement in the way that the class can be used. Why am I saying this? Well, as you’ll realize, now it’s feasible to call the class’s method statically without having to create any objects from it. Simple and efficient. But I’m not trying to sell you this simple helper class here. Instead, I’d like to show you how to use it now that its methods have been defined as static. Therefore, in the last section of this tutorial I’m going to create another example to demonstrate a proper usage of the text helper class, this time by calling its methods out of the object scope. To see how this final example will be developed, please click on the link below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|