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

How to Obtain Class Name in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 21:15:30620browse

How to Obtain Class Name in PHP?

Acquiring Class Name in PHP

In Java, the SimpleName for a class can be obtained using the MyClass.class.getSimpleName() syntax. In PHP, retrieving the class name for an object is possible using get_class(). However, accessing it directly from the class itself, like MyClass::className, requires a different approach.

PHP 5.5 and Later versions:

Starting from PHP 5.5, the ClassName::class syntax can be used to resolve class names. For example:

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

class ClassName {}

echo ClassName::class;</code>

This will output the class name as NameSpaceClassName.

PHP versions before 5.5:

For older versions of PHP, you can utilize the get_class() function, but this only works for objects. If you require a class name, consider using a dedicated class name constant, like:

<code class="php">class ClassName {
    const CLASS_NAME = 'ClassName';
}

echo ClassName::CLASS_NAME;</code>

Alternatively:

Another option is using static::class within class methods:

<code class="php">class ClassName {
    public function getNameOfClass() {
        return static::class;
    }
}

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

The above is the detailed content of How to Obtain 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