Alex Rohleder
Alex Rohleder

Reputation: 37

How to get the namespace where a function is called?

Is there a way to make this to work?

<?php

namespace Bar {
    class test {
        public function test($action) {
            call_user_func($action); // must call \Foo\Action
        }
    }
}

namespace Foo {
    $test = new \Bar\Test;

    function action () {
        echo 'it works!';
    }

    $test->test('action');
}

For a more detailed description: If I have a function that call user defined functions with de call_user_func, and uses that function in a Foo namespace to call a Foo namespaced function, how can I know that this passed function is on Foo namespace?

Upvotes: 1

Views: 43

Answers (2)

Rizier123
Rizier123

Reputation: 59691

You could use the constant __NAMESPACE__ and pass it as argument, e.g.

$test->test("\\" . __NAMESPACE__ . '\\action');

Upvotes: 2

deceze
deceze

Reputation: 522195

If you pass a function around by name in a string, you always need to use the fully qualified name including namespace. 'action' refers to the function \action. Even within the same namespace this won't work correctly. You need to use 'Foo\action' under all circumstances.

If you don't like hardcoding the namespace name, use __NAMESPACE__ . '\\action'.

Upvotes: 2

Related Questions