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

How to Obtain Class Name in PHP?

Barbara Streisand
Release: 2024-10-19 21:15:30
Original
666 people have browsed it

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

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

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

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!

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