Reputation: 52601
Is it possible to define a global function from within a PHP namespace (within a file that has a namespace declaration)? If so, how?
<?php
namespace my_module;
# bunch of namespaced functions
# ...
# then I want to define a global function my_module()
# that is an alias to my_module\mymodule()
Upvotes: 28
Views: 11223
Reputation: 101
Functions defined in 'included' files have global scope.
So ( I haven't verified this ) you could put your function declaration in a small file, and include it.
Not quite what was envisaged in the question.
The other way to do it would be to create a local function, and in it use the 'global' keyword, and assign a closure to a global variable - which could then be used 'as a function' wherever you wanted it. I've certainly done this for ordinary variables, and I see no reason it should not work for closures.
Upvotes: 2
Reputation: 69977
It's possible but aside from being bad design, you will have to enclose your code within brackets for each namespace and won't be able to use namespace my_module;
Instead it will have to be namespace my_module { ... }
.
Example:
namespace my_module {
function module_function()
{
// code
}
}
namespace {
// global namespace.
function my_module()
{
// call your namespaced code
}
}
Upvotes: 39