As I said in the segment that you just read, there’s another scenario where a private constructor can be truly useful -- when building a class that must be used out of the object context, or expressed in other words, as a solely static class. To demonstrate this concept, in the lines to come I’m going to code a presentational helper, which will be tasked with rendering different controls of an HTML form. Since there won’t be a real need to create instances of it, its originating class will have to be used only statically. How will this be accomplished? Yes, you guessed right! By declaring its constructor private and its discrete methods static, the helper will be turned into a static class. Now, take a look at the helper’s definition, which is as follows: <?php
class Form {
// private constructor private function __construct(){}
// render <form> opening tag public static function open(array $attributes = array()) { $html = '<form'; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('action', 'method', 'id', 'class', 'enctype')) and !empty($value)) { // assign default value to 'method' attribute if ($attribute === 'method' and ($value !== 'post' or $value !== 'get')) { $value = 'post'; } $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>'; }
// render <input> tag public static function input(array $attributes = array()) { $html = '<input'; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('type', 'id', 'class', 'name', 'value')) and !empty($value)) { $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>'; }
// render <textarea> tag public static function textarea(array $attributes = array()) { $html = '<textarea'; $content = ''; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('rows', 'cols', 'id', 'class', 'name', 'value')) and !empty($value)) { if ($attribute === 'value') { $content = $value; continue; } $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>' . $content . '</textarea>'; }
// render </form> closing tag public static function close() { return '</form>'; } }// End Form class Aside from implementing a few simple static methods that allow you to render common elements of a web form, such as input boxes, submit buttons and text areas, the previous “Form” class declares its constructor private. In doing so, the class can only be used out of the instance context. Having demonstrated yet another concrete use of a restrictive constructor in PHP 5 classes, it’s time to give the previous helper a try, so you can see how it functions. Therefore, in the final section of this tutorial I’m going to set up an example for you, which will show the earlier “Form” class in action. Now, jump forward and read the next segment. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|