cpxxxw
Last Updated: March 18, 2017
·
27.47K
· markus-perl
10620301 745710515470370 5763874756421604255 o

PHP get class name without namespace

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

6 Responses
Add your response

14077
Ebf13dd4fa9b7010e5ffd9042091e375

public function getName() {

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

}

over 1 year ago ·
17233

ReflectionClass is actually faster;

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

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 ·
19314
5c2d0d0b4cd3457db67aefcf03fd0d01

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 ·
20927
0 gh1iiruwxfjcd9uwk2isideemfjwfbbqehwi6fawxuqofbo6xobiir6ejdocdfoox2iisz5h9iveupowsu90ifkxpiviupmfhu9hhaldzofbq5vuko8m8sx41yhrlpj9t4tfbpd2t4v

fastest solution so far

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

why not
class_basename($objectOrString); ?

over 1 year ago ·