Join my Laravel for REST API's course on Udemy 👀

PHP: Get the class name of an object without namespace

July 27, 2022  ‐ 1 min read

We can get the qualified namespaced class name of an object by using the get_class() function. Assuming that our object's class has a namespace at least. If we wish to get just the class name we can use the reflection class to get the short name of the class.

>>> get_class($obj);
=> "App\Models\Project"
>>> (new \ReflectionClass($obj))->getShortName();
=> "Project"

Another option would be to actually get the qualified namespaced class name of the object and get the class name via string manipulation.

>>> end(explode('\\', get_class($obj)));
=> "Project"

Do note that we need to escape the backslash.