To start explaining how to build a helper in PHP 5, I'm going to define a basic class, which will be responsible for applying different filters to an entered string. The functionality of this introductory class will be progressively enhanced, so for the moment its initial signature will look as simple as this: class TextHelper { // constructor (not implemented) public function __construct(){}
// convert new lines to '<br />' tags in string public function newline_br($str) { if (is_string($str) AND empty($str) === FALSE) { return nl2br($str); } }
// convert new lines to '<p>' tags in string public 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>'; } } } As depicted above, the brand new "TextHelper" class has been provided with a couple of public methods for replacing all of the new lines within an incoming string with"<br />'" and "<p>" tags respectively. Also, the last of these two methods, called "newline_par()," has an additional functionality: it permits you to assign typical "id" and "class" attributes to the paragraphs being constructed. This ability makes it suitable to be used when displaying dynamic HTML pages. So far, everything looks good and easy to grasp, right? As you saw before, the "TextHelper" class performs a few simple text-formatting tasks, which should give you a clear idea of how to build this kind of class in PHP 5. I have to admit, though, that the class in its current incarnation doesn't help very much in reality. That means that it's time to extend its existing functionality. In the following section, I'm going to add more methods to the previous helper class. Specifically, I'm going to give it more text-formatting options. Thus, to see how these methods will be defined, click on the link shown below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|