PHP 5 Helpers: Calling Methods Out of Object Scope

Theoretically defining the role of helper classes in PHP 5 (and other popular server-side scripting languages) is a pretty approachable process. As their name suggests, helper classes provide developers with a set of logically-grouped methods that allow them to easily perform certain repetitive tasks that are common to different web applications. This is the second part of an eight-part article series that shows you how to build a variety of useful helper classes and expand on their functionality.

Typical examples of helper classes are those that dynamically build portions of a URL and validate incoming data, or that apply specific text-formatting filters to a supplied string before doing something useful with it, such as inserting it into a database table. Feel free to add your own to the list.

While everything looks good in theory when it comes to defining what a helper class is, things can get more complex when putting this definition into practice. This is especially true for inexperienced PHP programmers just starting to use the object-oriented paradigm for building web-based programs.

So, if you need to expand your existing skills as a PHP developer and wish to learn how to build helper classes with PHP 5 by means of a true hands-on approach, then begin reading this series of articles right now!

In the first part of this series, I offered a gentle introduction to creating a text helper class. This class was tasked with applying some basic filters to an inputted string. If you’ve already read that article, then it’s quite probable that you have a clear idea of how to build this kind of class in a relatively easy manner.

The methods of the class that I just mentioned were declared implicitly dynamic, even though it’s perfectly possible to call them statically, and the PHP engine won’t raise any errors about this process. However, it would be much better to declare these methods explicitly static, thus taking advantage of the functionality offered by the text helper class without having to spawn an instance of it.

Therefore, in this second part of the series I’m going to use a decent variety of code samples to explain how to improve the use of the text helper class developed before by turning its regular methods into static ones.

Want to see how this will be accomplished in a few basic steps? Then go ahead and start reading right away!

{mospagebreak title=Review: building a text helper class}

If you haven’t had the chance to read the introductory part of this series, where I went through the development of a basic text helper class with PHP 5, don’t worry; below I included the full source code of this class, so you can not only take a quick look at it, but quickly grasp how it works.

So, in summary, here’s how the class was initially defined, along with some examples regarding its proper usage:

class TextHelper

{

// constructor (not implemented)

public function __construct(){}

 

// convert new lines to ‘<br />’ tags

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>';

}

}

 

// convert new lines to ‘div’ tags in string (id and class attributes can also be specified)

public 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 function uppercase_all($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return strtoupper($str);

}

}

 

// lowercase all characters in string

public function lowercase_all($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return strtolower($str);

}

}

// uppercase first character in string

public function uppercase_first($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return ucfirst(strtolower($str));

}

}

}

 

 

// create an instance of TextHelper class

$txthelper = new TextHelper();

// convert new lines to ‘<br>’ tags

echo $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->uppercase_first(‘the shinning is a scary book of Stephen King!’);

/* displays the following

The shinning is a scary book of stephen king!

*/

As you can see above, I listed the complete signature of the “TextHelper,” along with a few easy-to-follow examples of how to use its methods for applying several filters to a sample string.

Aside from the ease of the examples in question, it’s valid to stress something here that becomes crucial to correctly using a helper class. As you may have noticed, in all the cases, the methods of the class have been called in the object context. Obviously, this implies that an instance of the class has been previously created. As I expressed in the introduction, however, this circumstance can be completely avoided by calling the methods statically.

Of course, the PHP engine will allow you to do this even when the methods haven’t been declared explicitly static, but this certainly may lead to an eventual misuse of the helper class.

To solve this issue, it would be much more effective to add a explicit “static” declaration to all of the class’s methods. This will prevent eventual calls inside an object context.

So, in the section to come I’m going to modify the initial definition of the “TextHelper” class by converting its regular public methods into static ones.

Logically, if you want to learn the full details of this conversion process, you’ll have to click on the link below and keep reading.

{mospagebreak title=Working with static methods}

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.

{mospagebreak title=The new text helper class in action}

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan