How do I check the class of an object within the PHP name spaced environment without specifying the full namespaced class.
For example suppose I had an object library/Entity/Contract/Name.
The following code does not work as get_class returns the full namespaced class.
If(get_class($object) == 'Name') {
... do this ...
}
The namespace magic keyword returns the current namespace, which is no use if the tested object has another namespace.
I could simply specify the full classname with namespaces, but this seems to lock in the structure of the code. Also not of much use if I wanted to change the namespace dynamically.
Can anyone think of an efficient way to do this. I guess one option is regex.
You may get an unexpected result when the class doesn't have a namespace. I.e.
get_class
returnsFoo
, then$baseClass
would beoo
.This can easily be fixed by prefixing
get_class
with a backslash:Now also classes without a namespace will return the right value.
Found on the documentation page of get_class, where it was posted by me at nwhiting dot com.
But the idea of namespaces is to structure your code. That also means that you can have classes with the same name in multiple namespaces. So theoretically, the object you pass could have the name (stripped) class name, while still being a totally different object than you expect.
Besides that, you might want to check for a specific base class, in which case
get_class
doesn't do the trick at all. You might want to check out the operatorinstanceof
.I use this:
I found myself in a unique situation where
instanceof
could not be used (specifically namespaced traits) and I needed the short name in the most efficient way possible so I've done a little benchmark of my own. It includes all the different methods & variations from the answers in this question.A list of the of the entire result is here but here are the highlights:
$obj->getShortName()
is the fastest method however; using reflection only to get the short name it is almost the slowest method.'strrpos'
can return a wrong value if the object is not in a namespace so while'safe strrpos'
is a tiny bit slower I would say this is the winner.'basename'
compatible between Linux and Windows you need to usestr_replace()
which makes this method the slowest of them all.A simplified table of results, speed is measured compared to the slowest method:
Quoting php.net:
Based on this info and expanding from arzzzen answer this should work on both Windows and Nix* systems:
Note: I did a benchmark of
ReflectionClass
againstbasename+str_replace+get_class
and using reflection is roughly 20% faster than using the basename approach, but YMMV.You can use
explode
for separating the namespace andend
to get the class name: