Home  >  Article  >  Backend Development  >  How to Retrieve Class Name in PHP?

How to Retrieve Class Name in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 21:18:30812browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn