Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class belongs to a certain namespace

I'm wondering if PHP provides a native way to check whether a class (instance) belongs to a certain namespace or not.

It doesn't really matter but just for your understanding how I came up with this question:

Using ZF2, I've got an event handler for the onDispatch event. However, this handler is invoked for every dispatch of any controller of any module. Obviously, I only want to perform an action in this handler if a controller of this module is being dispatched.

So I wanted to check whether the Controller is inside my module's namespace or not.

Btw, I solved this temporarily using a string compare on the class name (strpos($className, 'ModuleName\Controller') !== false). I guess that using substr() or strncmp() or something like that performs better than strpos(), but it doesn't really matter in my case.

Thanks in advance!

// Edit: To be clear, I'm looking for something like:

// $foo is an instance of MyApp\Controller\Moo
is_in_namespace('MyApp\Controller', $foo); // true

or

// $foo is an instance of MyApp\Controller\Moo
get_namespace($foo) === 'MyApp\Controller'; // true
like image 780
Daniel M Avatar asked Jan 08 '13 15:01

Daniel M


2 Answers

You can use get_class() to obtain the class of the object, then you can use strops() on it to find out if it contains the namespace. There isn't an equivalent get_namespace() function.

Example:

function is_in_namespace($namespace, $object) {
    return strpos(get_class($object), $namespace . '\\') === 0;
}
function get_namespace($object) {
    $class = get_class($object);
    $pos = strrpos($class, '\\');
    return substr($class, 0, $pos);
}
like image 114
rid Avatar answered Oct 13 '22 00:10

rid


Yes, ReflectionClass have getNamespaceName():

(new \ReflectionClass($foo))->getNamespaceName();
like image 43
celsowm Avatar answered Oct 13 '22 00:10

celsowm