I was wondering if it was possible to determine what the current namespace was when the function was being called. I have this function declaration:
<?php
namespace Site\Action;
function add ($hook, $function) {
/**
* determine the namespace this was called from because
* __NAMESPACE__ is "site\action" :(
*/
if (is_callable($function))
call_user_func($function);
}
?>
And on another file:
<?php
namespace Foo;
function bar () {
}
?>
And let’s say I have this as my procedural code:
<?php
namespace Foo;
Site\Action\add('hookname', 'bar');
?>
It would make sense to assume that Bar in this case was intended to resolve as Foo\bar since that was the namespace it was called from.
That was a long explanation so again, is it possible to determine the active namespace where Site\Action\add() was called from?
Thanks in advance.
What you are looking for is : ReflectionFunctionAbstract::getNamespaceName
If you want to know where you’re coming from debug_backtrace() is your friend.
The following should solve your puzzle:
Just call it from anywhere to see the backtrace.
I modified your “procedural” code file as follows:
The Result from including this file will be the following on stdout:
Now for bonus points the answer to the hidden question:
How do I resolve the calling namespace to avoid using fully qualified function name as argument?
The following will allow you to call the function as you intended:
Without getting the dreaded:
So before you redesign try this on for size:
I see no reason why
debug_backtraceshould not be used, this is what it is there for.nJoy!