Last Updated: February 25, 2016
· silasribas

Get class name without namespace

When using get_class with a class and her have a namespace definition, this function return the fully class name, including the namespace:

Example 1 - class without namespace definition:

// foo.php
class Foo {}

$foo = new Foo;
echo get_class($foo); // Foo

Example 2 - class with namespace definition:

// foo/bar.php
namespace Foo;

class Bar {}

// example2.php
$bar = new \Foo\Bar;
echo get_class($bar); // Foo\Bar

In case of Example 2, if you desire to get the class name without namespace, you use reflection with the class called ReflectionClass:

// foo/bar.php
namespace Foo;

class Bar {}

// example3.php
$bar = new \Foo\Bar;
$reflection = new \ReflectionClass($bar);
echo $reflection->getShortName(); // Bar

Good luck!