Preventing namespace clashes in PHP

PHP LogoThe PHP scope resolution operator in PHP is a useful feature when you need to access methods or variables within a static context. It can often be useful in reducing namespace conflicts. Especially when using custom code with off the shelf systems to avoid conflicting function redefinitions.

There have been a few cases where previously defined function errors have cropped up when adding a pre made system to a custom developed application. This is has been most prominent with Word press or any system which has generically named functions. It’s often unavoidable to prevent function clashes as it requires knowing any other external system definitions which of course isn’t always possible.

Keeping generic function names in a class is a possible option to reduce the problem; however this brings about the requirement of instantiating a class before being able to use the function. Another way to get around this issue is to use the scope resolution operator to statically call functions or even properties. In PHP this can be achieved using the scope resolution operator, otherwise known as the double colon operator.

Example:

class foobar {
public static function call_me() {}
}

Usage:

foobar::call_me();

The scope resolution operator should be used wisely. It is often best practice to only use static methods when they are stateless in nature, i.e. basic helper functions that do not modify any external state beyond their own contained execution.