Which is the best/right way if I want to create a Helper class in PHP?
A Helper class that contains static methods like this:
<?php
class Helper {
static function helpThis() {
// code
}
static function helpThat() {
// code
}
}
?>
Or
开发者_开发技巧Create a PHP file with a bunch of functions like this:
<?php
function helpThis() {
// code
}
function helpThat() {
// code
}
?>
I'd suggest creating a class.
This way you can save yourself from adding include helper.inc.php
everytime before using these functions.
Class on the other hand can be autoloaded: Helper::helpThis()
and that's it.
I guess it's always 'better' to put the methods in a class. Not only does it look better, but when using classes it's easier to know what every function/method does. You could for example create a main helper class and several other helper classes that derive from the main class. Everything is in place then and clear to understand what it does. ;)
I can think of some good reasons to prefer a class with static methods over functions.
More context. The class name itself is providing more context than just a function name does. If you try to provide the same information with a function you end up with pretty verbose function names. Consider the following example:
UserTemplateHelper::printId($user); // ... VS ... userTemplateHelperPrintId($user);
What people generally do is get lazy so the function names usually are not verbose like the one shown above. That's why you may end up providing less context. Your code would therefore be less readable. Also if you want to change
UserTemplateHelper
into something else, is rather easier changing just a class name than a lot of functions with that prefix.Autoload VS include. includes and requires usually make applications more error-prone. They are also annoying to use since it's just another thing type. Also, what they do for sure is creating a less maintainable application since you may end up having includes spread everywhere versus one autoload. I think it's usually best to centralise logic.
Shared variables. You may want to share some variables between your functions later on. It's easier to do such thing by declaring a private static variable rather than using the hard-to-debug and usually evil
global
keyword.
精彩评论