With the release of PHP 5.3 namespaces became a reality in PHP and they’ve made so much possible including better autoloading. The majority of the time you’ll be used to seeing them at the top of each class file. They can also be used to namespace functions however.
A standard PHP namespace declaration would look similar to the following at the top of a class file.
namespace Treffynnon\Html;
class Tag {
// ...
}
In this scheme you should not have multiple namespaces in the same file - generally frowned upon anyway as class files should really only include the one class declaration.
Namespaces can actually wrap code - rather than just being declared at the top of files. There is an unbracketed syntax too, but I don’t like it so I am not going to use it here. I much prefer the clear boundaries of the wrapping braces and some indentation.
namespace Treffynnon\Html {
function get() {
return '';
}
}
You can also have multiple namespaces in the same file this way although I would not recommend this in practice much like I don’t like multiple classes in the same PHP file.
namespace Treffynnon\Html {
function get() {
return '';
}
}
namespace Treffynnon\Utils {
function get() {
return '';
}
}
If you want to dip back into the global namespace you can do so by specifying a namespace without an explicit name.
namespace Treffynnon\Html {
function get() {
return '';
}
}
namespace {
function get() {
return '';
}
}
I have found this especially helpful in Drupal or Wordpress where you have hook functions that get called from/in the global namespace. These functions can be treated as entry points with the bulk of the actual code inside a module specific namespace.
namespace {
use MyProject\MyModule as M;
function my_module_menu() {
return M\get_menu();
}
}
namespace MyProject\MyModule {
function get_menu() {
return [
// some Drupal menu implementation goes here
];
}
}
This is a bit of a flimsy example, but you can see how it can be used to isolate your code from the huge global space of Drupal. It is more helpful with hooks that change the page or node and in the case of data a view. Wordpress is similar in this regard so I won’t go into more detail.
I have written an addendum to this post that covers importing and aliasing functions with
PHP’s namespace keywords (use
and as
).