4

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()
    }
}
5
  • Is there a special reason you don't want Reflection? Besides that, if you have the class name as string you can use PHP's string functions on it. Commented Mar 19, 2018 at 8:31
  • Create class property with class name and use it)))) Commented Mar 19, 2018 at 8:33
  • replace ____NAMESPACE____ in getclass? Commented Mar 19, 2018 at 8:35
  • 1
    Find the last occurrence of \ and take everything after it… php.net/manual/en/ref.strings.php Commented Mar 19, 2018 at 8:47
  • I see the comments and answers using str_replace but I full expected PHP to offer a cleaner way of doing that rather than having to rely on string manipulation. Commented Mar 20, 2018 at 2:06

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cannot use end without declaring a variable. Is there an alternative to get the last element?
4

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

<?php

echo class_basename(__CLASS__);

3 Comments

The class_basename() function does not exists.
class_basename is a function from Laravel, not from PHP itself.
well, I'm using Laravel, and I was looking for this. Grazie @LucaMurante :-)
2

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…

Comments

2

This is the fastest method I've came up with and seems to be working for all cases:

function toUqcn(string $fqcn) {
   return substr($fqcn, (strrpos($fqcn, '\\') ?: -1) + 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.