Reputation: 269
Calling get_called_class()
in PHP from a static function gives you the class name of the function, including the namespace if called from outside that namespace, it seems.
Is there a way to acquire the class name without the namespace?
(Obviously I understand that it would be possible to examine the string returned by get_called_class()
and do some hackish stuff, but I am hoping there is a less hackish way to do it)
Upvotes: 4
Views: 3378
Reputation: 392
You can use:
/**
* Get the class "basename" of the given object / class.
*
* @param string|object $class
* @return string
*/
function class_basename($class)
{
$class = is_object($class) ? get_class($class) : $class;
return basename(str_replace('\\', '/', $class));
}
Upvotes: 0
Reputation:
Acquiring the class name without a namespace
Yes, you can do it using the ReflectionClass. Since your question relates to doing this from within a static method, you can get the class name like so:
$reflect = new \ReflectionClass(get_called_class());
$reflect->getShortName();
This uses the ReflectionClass constructor by passing a string with the fully namespaced name of the class to be inspected.
There is a similar question at How do I get an object's unqualified (short) class name? however it does not refer to doing this within a static method and so the examples pass an instantiated object to the ReflectionClass constructor.
Upvotes: 8