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 can do this with reflection. Specifically, you can use the
ReflectionClass::getShortName
method, which gets the name of the class without its namespace.First, you need to build a
ReflectionClass
instance, and then call thegetShortName
method of that instance:However, I can't imagine many circumstances where this would be desirable. If you want to require that the object is a member of a certain class, the way to test it is with
instanceof
. If you want a more flexible way to signal certain constraints, the way to do that is to write an interface and require that the code implement that interface. Again, the correct way to do this is withinstanceof
. (You can do it withReflectionClass
, but it would have much worse performance.)Here is a more easier way of doing this if you are using Laravel PHP framework :
I know this is an old post but this is what i use - Faster than all posted above just call this method from your class, a lot quicker than using Reflection
I added substr to the test of https://stackoverflow.com/a/25472778/2386943 and that's the fastet way I could test (CentOS PHP 5.3.3, Ubuntu PHP 5.5.9) both with an i5.
Results
Code
==UPDATE==
As mentioned in the comments by @MrBandersnatch there is even a faster way to do this:
Here are the updated test results with "SubstringStrChr" (saves up to about 0.001 s):
The fastest and imho easiest solution that works in any environment is: