Tag Archives: Namespace

How to use PHP’s namespaces and constants within your WordPress plugins

Recently I switched from using a class to emulate a namespace in my WordPress plugins to actually using PHP’s namespace, which is available in PHP 5.3.0 or greater. I’m going to demonstrate some things that all my plugins thus far have in common.

1. Create a namespace

Right before your plugin meta data comment, you must lead with your namespace (otherwise PHP will complain):

1
namespace CompanyName\PluginName;
namespace CompanyName\PluginName;

I use a master namespace for everything I do (CompanyName) and a sub-namespace for the specific plugin I’m working on (PluginName).

2. Define a namespace constant

After the plugin meta data comment I define a constant, in other words, a shortcut to reference my namespace within WordPress hooks. It’s just less to type in the future and I can change my namespace without affecting plugin functionality.

1
define(__NAMESPACE__ . '\NS', __NAMESPACE__ . '\\');
define(__NAMESPACE__ . '\NS', __NAMESPACE__ . '\\');

What this allows me to do is use a constant called NS to render CompanyName\PluginName\ so that after leading with NS in a WordPress hook callback, all I need to provide is my function name.

To create additional constants within your namespace, you can do that like so:

1
define(NS . 'PS', 'plugin-slug');
define(NS . 'PS', 'plugin-slug');

3. Use your namespace constant in a WordPress hook

Here is what a function and a hook looks like in a namespaced environment:

1
2
3
4
5
6
7
8
function initialize_plugin() {
 
}
 
add_action(
  'init',
  NS . 'initialize_plugin'
);
function initialize_plugin() {

}

add_action(
  'init',
  NS . 'initialize_plugin'
);

It’s really not that much different compared to not using a namespace and it certainly looks a lot cleaner than if you were using a class.

4. Use core WordPress functions

There are times where you need to use WordPress functions like the register_activation_hook, for example. It’s important to remember to change the namespace back to the global namespace for those functions.

The way to do that is to precede the function with a backslash:

1
\register_activation_hook(__FILE__, NS . 'register_activation_hook');
\register_activation_hook(__FILE__, NS . 'register_activation_hook');

This should get you started and if you have any questions, leave them in the comments below.