Namespaces are used to avoid collisions with functions (as well as constants and class names) in PHP.
Prefixing Functions (before Namespaces)
Before namespaces (using PHP 5.2 and below), when creating a function called output_form()
I ran the chance that someone else had the same function name defined somewhere else. This would result in a fatal error.
Fatal error: Cannot redeclare output_form()
To work around this, I would prefix it with both salcode
and my project name (e.g. modify_comment
) so instead of output_form()
, the function was salcode_modify_comment_output_form()
.
Namespacing Functions
As of PHP 5.3, we can add a namespace instead of prefixing. Instead of salcode_modify_comment_output_form()
, I can write
namespace salcode\ModifyComment;
function output_form() {
// Code here.
}
output_form();
By adding namespace salcode\ModifyComment;
at the top of my file, it is as if I’ve prefixed all of the functions in the file (so I no longer have to worry about collisions).
Files in Other Namespaces
What if I want to use my output_form()
function from a file that is NOT in the namespace salcode\ModifyComment
?
The easiest way to target a function in another namespace is to use the fully qualified name (i.e. the namespace and function name together). When we do this we start the line with a leading slash (\
), this tells PHP this namespace and function are independent of any namespace defined for the current file.
echo \salcode\ModifyComment\output_form();
WordPress Hooks and Filters with Namespaces
There are some nuances to using namespaces with WordPress Hooks and Filters. See my other blog post WordPress Hooks and PHP Namespaces for more details.
Leave a Reply