Home > Article > Backend Development > How to Retrieve Class Name in PHP?
Getting Class Name in PHP
In Java, one can obtain the name of a class using String className = MyClass.class.getSimpleName();. How can this be achieved in PHP, especially when working with Active Record and requiring a statement like MyClass::className?
Answer:
Since PHP 5.5, class name resolution is possible through ClassName::class. This feature enables you to determine the name of a class as follows:
<code class="php"><?php namespace Name\Space; class ClassName {} echo ClassName::class; ?></code>
If you want to utilize this feature within a class method, use static::class:
<code class="php"><?php namespace Name\Space; class ClassName { /** * @return string */ public function getNameOfClass() { return static::class; } } $obj = new ClassName(); echo $obj->getNameOfClass(); ?></code>
For earlier versions of PHP, you can employ get_class().
The above is the detailed content of How to Retrieve Class Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!