Xeoncross
Xeoncross

Reputation: 57224

How to detect the last namespace used in PHP?

If I had two classes in separate namespaces (and therefor files), and they both called a function in the global namespace - is there any way to indentify which namespace called that function short of passing the value?

namespace A;
class Test { function run() { \func(); }

...

namespace B;
class Test { function run() { \func(); }

...

function func()
{
    // Did a class from "\A" call me or "\B"...?
}

My first thought was to use the __NAMESPACE__ constant. But that is computed in place so it would not solve this problem.

Upvotes: 2

Views: 280

Answers (2)

CLo
CLo

Reputation: 3730

You could define versions of the function in each namespace that then calls func();

namespace A;
class Test { function run() { func(); }

...

namespace B;
class Test { function run() { func(); }

...

namespace A
{
    function func()
    {
        \func(__NAMESPACE__);
    }
}

namespace B
{
    function func()
    {
        \func(__NAMESPACE__);
    }
}

namespace 
{
    function func($namespace)
    {
        //work with $namespace
    }
}

Upvotes: 2

CLo
CLo

Reputation: 3730

debug_backtrace() will show you the call stack. It also gives you the class name of the object that the calls were made from. You could parse this date out and find the namespace.

http://www.php.net/manual/en/function.debug-backtrace.php

function func()
{
    $trace = debug_backtrace();
    $class = $trace[1]['class']; //Should be the class from the previous function

    $arr = explode($class, "\");
    array_pop($arr);
    $namespace = implode($arr, "\");
}

Let me know if that works. It will probably only work if func() is called from inside an object or class.

Upvotes: 1

Related Questions