Since my purpose here is to extend the functionality of the string processor in the previous section, I'm going to implement yet another chainable method. In this case, it will be tasked with lowercasing the characters of an inputted string. Having explained that, here's the enhanced version of the "StringProcessor" class, after including the method previously mentioned: class StringProcessor { private $str = ''; private static $instance = NULL;
// constructor public function __construct($str = 'This is a default string') { $this->str= $str; }
// trim white space from input string // chainable public function trim_space() { $this->str = trim($this->str); return $this; }
// uppercase input string // chainable public function str_upper() { $this->str = strtoupper($this->str); return $this; }
// lowercase input string // chainable public function str_lower() { $this->str = strtolower($this->str); return $this; }
// get input string public function get_string() { return $this->str; } } Here you have it. Now the above class implements a new method called "str_lower()" that's charged with lowercasing the inputted string accepted by the class. Of course, the most relevant point to spot here is that this method is also chainable, meaning that it's possible to use it in conjunction with the previous ones to parse a sample string. This process is illustrated by the code sample below. $strproc = new StringProcessor(' HELLO, THIS IS A SIMPLE EXAMPLE OF METHOD CHAINING IN PHP '); // process string by chaining 3 methods echo $strproc->trim_space()-> str_lower()-> get_string(); /* displays the following hello, this is a simple example of method chaining in php */ From the previous example, it's clear to see how easy it is to code and use the "str_lower()" method defined earlier. Also, you should notice how compact and tight the code is when an instance of the "StringProcessor" class is utilized to make the sample string all lower case. At this point, I'm pretty sure that you grasped the logic implemented by the "str_lower()" method, as well as the way it's been turned into a chainable interface component. Therefore, in the last segment of this tutorial I'm going to extend the functionality of the string processor even more, by means of another chainable method. To learn more about how this will be accomplished, go ahead and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|