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.
If you need to know the class name that was called from inside a class, and don't want the namespace, you can use this one
This is great when you have a method inside a class which is extended by other classes. Furthermore, this also works if namespaces aren't used at all.
Example:
To get the short name as an one-liner (since PHP 5.4):
It is a clean approach and reasonable fast.
Here is simple solution for PHP 5.4+
What will be return?
Extended class name and namespace works well to:
What about class in global namespace?
A good old regex seems to be faster than the most of the previous shown methods:
So this works even when you provide a short class name or a fully qualified (canonical) class name.
What the regex does is that it consumes all previous chars until the last separator is found (which is also consumed). So the remaining string will be the short class name.
If you want to use a different separator (eg. / ) then just use that separator instead. Remember to escape the backslash (ie. \) and also the pattern char (ie. /) in the input pattern.
If you're just stripping name spaces and want anything after the last \ in a class name with namespace (or just the name if there's no '\') you can do something like this:
Basically it's regex to get any combination of characters or backslashes up and until the last backslash then to return only the non-backslash characters up and until the end of the string. Adding the ? after the first grouping means if the pattern match doesn't exist, it just returns the full string.
(new \ReflectionClass($obj))->getShortName();
is the best solution with regards to performance.I was curious which of the provided solutions is the fastest, so I've put together a little test.
Results
Code
The results actually surprised me. I thought the explode solution would be the fastest way to go...