While PHP namespaces allow you to refer to a function in file without using the fully qualified name, there is a catch when adding a WordPress hook or filter.
Functions in the Same File
When you define a namespace for a file, it applies to the entire file.
Therefore if I define a function and call it in the same file, I can use just the function name (output_form
) instead of the fully qualified name (\Salcode\ModifyComment\output_form
).
namespace Salcode\ModifyComment;
function output_form() {
// code here
}
output_form();
Adding a Function to a WordPress Hook
However, if we’re adding the function to a WordPress hook we do need to use the fully qualified name.
namespace Salcode\ModifyComment;
function output_form() {
// code here
}
add_action( 'wp_footer', '\Salcode\ModifyComment\output_form' );
If we had used just output_form
, it would NOT have worked.
// This does NOT work.
add_action( 'wp_footer', 'output_form' );
Shortcut When Adding the Function to a Hook
We can use the PHP __NAMESPACE__ magic constant, which is a string that contains the current namespace name.
Now our code can be written
namespace Salcode\ModifyComment;
function output_form() {
// code here
}
add_action( 'wp_footer', __NAMESPACE__ . '\output_form' );
In addition to often being shorter, this has the advantage that we would not have to update the namespace in two locations if we decided to change the namespace in this file.
Why Does this Happen?
When we add a function to a WordPress hook or filter, we are actually passing in a string to the add_action()
(or add_filter
) function. WordPress holds on to this string and at the appropriate time runs the function that matches the name stored in the string. Since WordPress runs this code in a different location (and that file does not have the same namespace), it would not be able to find our function if we did not give it the fully qualified name of the function.
Sal,
Thanks for sharing! When I was first learning OOP this took me way longer to figure out than I care to admit lol. I still often forget to \ when using something from outside the current class.