Last Updated: February 12, 2021
·
175.4K
· markus-perl

PHP get class name without namespace

public function getName() {
    $path = explode('\\', __CLASS__);
    return array_pop($path);
}

9 Responses
Add your response

public function getName() {

return substr(strrchr(__CLASS__, "\\"), 1);    

}

over 1 year ago ·

ReflectionClass is actually faster;

(new \ReflectionClass($this))->getShortName();
over 1 year ago ·

It was a big surprise to me, but reflection is actually much faster than the other two.

Here is the result:

Method Name      Iterations    Average Time      Ops/second
--------------  ------------  --------------    -------------
testExplode   : [10,000    ] [0.0000020221710] [494,518.01547]
testSubstring : [10,000    ] [0.0000017177343] [582,162.19968]
testReflection: [10,000    ] [0.0000015984058] [625,623.34059]

I have to mention that if I run the tests only once (no iterations, but several runs and making an avarage), the substring solution is the winner in speed. (This is probably because reflection is cached)

Actually the original solution is the slowest of all.

over 1 year ago ·

Using the CLASS constant generally works, however it fails if used in a child class of a class which uses a trait:

trait ClassDetector
{
    public function getClassName()
    {
        return __CLASS__;
    }
}

class Foo
{
    use ClassDetector;
}

class Bar extends Foo
{
}

$bar = new Bar;

// returns Foo
$bar->getClassName();
over 1 year ago ·

fastest solution so far

return (substr($classname, strrpos($classname, '\\') + 1));
over 1 year ago ·

why not
class_basename($objectOrString); ?

over 1 year ago ·

@filpgame
why not
class_basename($objectOrString); ?

class_basename is over 10x slower on my machine anyway

using this script

$time = microtime(true);
for($i=0; $i < 1000000; ++$i){
//$a=explode('\', CLASS); arraypop($a);
// 0.29 sec
substr(strrchr(
CLASS, "\"), 1);
// 0.15 sec
//(new \ReflectionClass($this))->getShortName();
// 0.35 sec
//class
basename(CLASS);
// 3.6 sec
}
var_dump([
$time,
microtime(true),
(microtime(true)-$time),
]);

over 1 year ago ·

You can do this with reflection.

$reflect = new ReflectionClass($object);
if ($reflect->getShortName() === 'Name') {
// do this
}

You can use ReflectionClass::getShortName which get name of the class without its namespace.

over 1 year ago ·

(new \ReflectionClass(getcalledclass()))->getShortName()

over 1 year ago ·