142
public class MyClass {

}

In Java, we can get class name with String className = MyClass.class.getSimpleName();

How to do this in PHP? I already know get_class(), but it works only for objects. Currently I work in Active Record. I need statement like MyClass::className.

3
  • 1
    Could you give a particular example when it might be helpful in php? If you have hardcoded the classname - you may wrap it in quotes and get what you want. Commented Feb 27, 2013 at 3:47
  • 2
    Unfortunately automatic refactorings (e.g. in IDEs) like RenameClass usually do not rename such class name strings. Therefore it would be nice to have some kind of static way to get the class name, aside from doing the public $__CLASS__ = __CLASS__; dance with every other class... Commented Mar 1, 2014 at 16:07
  • 2
    Possible duplicate of How can I get the classname from a static call in an extended PHP class? Commented Dec 4, 2017 at 10:12

11 Answers 11

167

Since PHP 5.5 you can use class name resolution via ClassName::class.

See new features of PHP5.5.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

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

4 Comments

What's the difference between static::class and get_class_name()?
@AlexanderJank It seems as though static::class is resolved during compile time while get_class_name() is interpreted during runtime. I found this out by trying to access the ::class property(?) of a dynamically generated class and getting the following error: Dynamic class names are not allowed in compile-time ::class fetch. See this answer for more details. I also found this note from the docs helpful.
Actually, this does not give you a string: $shortName = substr($class, strrpos($class, '\\') + 1); => Expected type 'string'. Found 'yii\db\ActiveRecord'
You can cast to string though: $shortName = substr((string) $class, strrpos((string) $class, '\\') + 1); => "ActiveRecord".
40

It sounds like you answered your own question. get_class will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class

Here is their example:

 <?php

 class foo 
 {
     function name()
     {
         echo "My name is " , get_class($this) , "\n";
     }
 }

 // create an object
 $bar = new foo();

 // external call
 echo "Its name is " , get_class($bar) , "\n"; // It's name is foo

 // internal call
 $bar->name(); // My name is foo

To make it more like your example you could do something like:

 <?php

 class MyClass
 {
       public static function getClass()
       {
            return get_class();
       }
 }

Now you can do:

 $className = MyClass::getClass();

This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.

<?php

class MyClass
{
    public static function getClass()
    {
        return get_called_class();
    }

    public static function getDefiningClass()
    {
        return get_class();
    }
}

class MyExtendedClass extends MyClass {}

$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'

1 Comment

Thanks @J.Money for the idea.. But it doesn't work in inheritance.
37

You can use __CLASS__ within a class to get the name.

http://php.net/manual/en/language.constants.predefined.php

5 Comments

you can also take a look here to view all interesting const : php.net/manual/en/language.constants.predefined.php
Thanks to @Brad for the link, I find the answer here
@user1073122, That's the link that I linked to in my answer.
+1 as I was trying to get the class name in a method that is defined in the parent class. Other solutions (get_class($this), static::class) simply returns the child (that extends the parent) class name.
continued: self::class, also, seems to return the parent class name.
26

It looks like ReflectionClass is a pretty productive option.

class MyClass {
    public function test() {
        // 'MyClass'
        return (new \ReflectionClass($this))->getShortName();
    }
}

Benchmark:

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]

Comments

14

To get class name you can use ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}

2 Comments

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Absolutely Special!!! This is a SUPER but simple solution! Thankss!!!!
11

Now, I have answer for my problem. Thanks to Brad for the link, I find the answer here. And thanks to J.Money for the idea. My solution:

<?php

class Model
{
    public static function getClassName() {
        return get_called_class();
    }
}

class Product extends Model {}

class User extends Model {}

echo Product::getClassName(); // "Product" 
echo User::getClassName(); // "User" 

3 Comments

It makes no sense. FooBar::getClassName() is always 'FooBar'. If you could type Product::getClassName() - then you could type 'Product' instead as well.
Yes I know.. I want to avoid typo and also when re-factoring the class name (with IDE tools), I don't need to search & replace the string.
This could also help if you need to use the class name of the child class in the parent "Model" class.
7

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

Comments

7

This will return pure class name even when using namespace:

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

Comments

2

end(preg_split("#(\\\\|\\/)#", Class_Name::class))

Class_Name::class: return the class with the namespace. So after you only need to create an array, then get the last value of the array.

Comments

1

From PHP 8.0, you can use ::class even on objects:

$object = new \SplPriorityQueue();

assert($object::class === \SplPriorityQueue::class);

Comments

0
<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5

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.