php – Get class name minus namespace without using Reflection-ThrowExceptions

Exception or error:

Is there a simple way to get the class name without the namespace without using Reflection?

This is my class and when I call get_class() I get CRMPiccoBundle\Services\RFC\Webhook\SiteCancelled

namespace CRMPiccoBundle\Services\RFC\Webhook;

class SiteCancelled extends Base implements Interface
    public function process() {
       // echo get_class()
How to solve:

Or simply exploding the return from class_name and getting the last element:

 $class_parts = explode('\\', get_class());
 echo end($class_parts);

Or simply removing the namespace from the output of get_class:

echo str_replace(__NAMESPACE__ . '\\', '', get_class());

Either works with or without namespace.

And so on.


So many ways to do it using string manipulation…

If you’re certain your class name contains a namespace:

$c = 'CRMPiccoBundle\Services\RFC\Webhook';

echo ltrim(strrchr($c, '\\'), '\\');
echo substr($c, strrpos($c, '\\') + 1);

If you’re uncertain whether the class may or may not contain a namespace:

echo ltrim(substr($c, strrpos($c, '\\')), '\\');

preg_match('/[^\\\\]+$/', $c, $m)
echo $m[0];

And probably many other variations on that theme…


Use the class_basename() function to get your class name without the namespace


echo class_basename(__CLASS__);

Leave a Reply

Your email address will not be published. Required fields are marked *