I try to avoid declaring functions in the global namespace altogether. The very rare occasions where I do this, is when adding userland implementations of functions that are not in my version of PHP, for instance
if(false === function_exists('lcfirst'))
{
function lcfirst( $str ) { /* ... */}
}
Functions like this could go in a utils.php which would be included in a bootstrap file, so they are available throughout the application and the check to function_exists
makes sure I don't run into issues once the PHP version has native support for the function.
For all other functions, I'd group them in a static module with the name Utils in a unique namespace, so they don't clutter up the global namespace. This way, you can be sure you are not clashing with other third party functions in the global scope.
Prior to 5.3, I'd group them following the PEAR naming convention and prefixing class names following your folder structure, for example if the module was in com/mattmueller/utils.php
, you'd use
class Com_MattMueller_Utils
{
public static function something($a, $b) { /* ... */ }
}
As of PHP5.3, we've got real namespaces and you can do
namespace com\mattmueller\Utils;
class Utils
{
public static function something($a, $b) { /* ... */ }
}
In Javascript you don't have namespaces but can easily simulate them by adding the functions to an object, e.g.
// JavaScript
var com = (com) ? com : {};
com.mattmueller = {
'Utils': {
'something' : function(a,b) { /* ... */ }
}
};
The common frameworks usually implement functions for creating namespaces as well.