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
Release: 2024-10-19 21:17:01
Original
566 people have browsed it

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 {
}
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

You can obtain the class name using:

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

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template