Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Revised PHP convenience functions (as an object)

Monday, February 21st, 2011 by Servage

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!

Revised PHP convenience functions (as an object), 3.7 out of 5 based on 7 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

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?

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.

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

Actually it works without declaring the function as static. Might be depending on PHP version.

This is very valuable for me. Thanks.

Leave a comment

You must be logged in to post a comment.