Home  >  Article  >  Backend Development  >  How Can I Get a Class Name in PHP?

How Can I Get a Class Name in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 21:19:29796browse

How Can I Get a Class Name in PHP?

Getting Class Name in PHP

Similar to Java, PHP provides various methods to retrieve the class name.

Using ClassName::class

With PHP version 5.5 and above, class name resolution can be achieved using the ClassName::class syntax:

<code class="php">namespace Name\Space;

class ClassName {}

echo ClassName::class;</code>

Using get_class()

For older versions of PHP, the get_class() function can be used:

<code class="php">class MyClass {

}

$className = get_class(new MyClass());</code>

Using static::class (For Class Methods)

Within a class method, the static::class syntax can be used to retrieve the class name:

<code class="php">namespace Name\Space;

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

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

The above is the detailed content of How Can I Get a 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