I want to keep my defined constants just inside the scope of my Wordpress plugin as I feel that a plugin should not be filling up the global namespace unless necessary.
I have a structure like:
namespace pluginname;
namespace pluginname\setup;
namespace pluginname\helpers;
etc...
I tried doing:
define('pluginname\var', 'foo');
and then in the child namespaces doing:
use pluginname;
But this does not bring the constant into scope. Is this the right approach but wrong syntax or vice versa?
Should I create a static definition class instead? I am coming from .NET background and getting a little confused with PHP implementation of namespaces and scoping.
What is the preferred approach?
You can't use use
to import constants in namespaces (FAQ).
Here is an example to understand, how you could do it:
namespace pluginname { // pluginname
define(__NAMESPACE__ . '\TEST', 'This my test constant.'.PHP_EOL);
echo TEST;
}
namespace pluginname\setup { // pluginname\setup
echo \pluginname\TEST;
}
namespace pluginname\helpers { // pluginname\helpers
echo \pluginname\TEST;
}
namespace { // global
echo pluginname\TEST;
echo TEST;
}
This would print:
This my test constant.
This my test constant.
This my test constant.
This my test constant.
TEST