Home >Backend Development >PHP Tutorial >How to Get Class Name in PHP (PHP 5.5 and Later)?

How to Get Class Name in PHP (PHP 5.5 and Later)?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 21:17:01567browse

How to Get Class Name in PHP (PHP 5.5 and Later)?

Getting Class Name in PHP

In PHP environments, obtaining the name of a class can be done using various methods. One common approach is to use the get_class() function. However, it is essential to note that get_class() is only applicable to objects, not class names.

For instance, if we have a class defined as:

public class MyClass {
}

In Java, we can retrieve the class name using: String className = MyClass.class.getSimpleName();. How can we achieve the same in PHP?

Using Class Name Resolution (PHP 5.5 and later)

PHP 5.5 introduced a feature called class name resolution, which allows you to obtain the class name directly. This can be done using the syntax: ClassName::class.

For example:

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

class ClassName {}

echo ClassName::class;</code>

This code will output the string "ClassName".

If you need to use this feature within a class method, you can use static::class.

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

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

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

Using get_class() (PHP versions older than 5.5)

For PHP versions prior to 5.5, the get_class() function can be utilized to obtain the class name. However, it is important to note that this function operates on objects, not class names.

For instance, if you have an instance of the "ClassName" class:

<code class="php">$obj = new ClassName();</code>

You can obtain the class name using:

<code class="php">echo get_class($obj);</code>

This code will output the string "ClassName".

The above is the detailed content of How to Get Class Name in PHP (PHP 5.5 and Later)?. 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