In this recent article I discussed the usage of PHP convenience functions in a class based, object oriented environment. Thanks to some great feedback from Rick Hambrook, I have revised the example, so it fits Rick’s suggestion. This implementation essentially gives the same functionality and usability, but wraps the convenience functions in a nice class. It looks better, and makes it easier to implement in other projects as well.
<? // Conv class (Convenience function collection) class Conv { // Timestamp method function timestamp($time = false) { if(!$time) { $time = time(); } return date('Y-m-d H:i:s', $time); } } ?>
Now you have a class with convenience functions that can be easily utilized across your application with:
Conv::timestamp();
If you have many convenience functions, bundling them according to Rick’s suggestions is a good idea.
Have fun coding!
5 comments (leave a comment)
Firstly, I’d like to say that I am a hobbyist when it comes to PHP and have limited experience. Baring that in mind. It seems like doing convenience functions globally or in a class just seems to me like finding different ways of doing the same thing.
My question is, what’s the difference?
doing the above call to a class method
Conv::timestamp();
versus a call to a global function
timestamp();
Either way the result is the same. Please help me understand what the difference is?
Reply by Jakob on March 2, 2011 at 09:22
The difference is that in one method you declare a global function. In the other, you collect your functions in a class. This makes it easier to organize many functions in a logic order.
by Jonathan Dreyfus on February 27, 2011 at 13:48
You can’t like this Conv::timestamp(); because this “::” is used to call a static function, the right way would be Conv->timestamp(); or in your class you may declare the function as a static function timestamp(){}
Anyway,
Regards,
Eriol Gjergji
Reply by Jakob on March 2, 2011 at 09:21
Actually it works without declaring the function as static. Might be depending on PHP version.
by Eriol Gjergji on February 28, 2011 at 10:57
This is very valuable for me. Thanks.
by Bleach Costumes on April 8, 2011 at 08:31