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
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);
}
Yes, ReflectionClass have getNamespaceName():
(new \ReflectionClass($foo))->getNamespaceName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With