Home >Backend Development >PHP Tutorial >How to Get a List of Defined Constants in a PHP Class?

How to Get a List of Defined Constants in a PHP Class?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 11:01:02941browse

How to Get a List of Defined Constants in a PHP Class?

How to Retrieve Defined CONSTs on a PHP Class

Question:

How can one obtain a list of CONSTs defined within a PHP class? Using the get_defined_constants() function proves insufficient.

Answer:

Leveraging the ReflectionClass interface provides a solution to this query. Repeated executions of this process may benefit from caching the resulting data.

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}

$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());

Output:

Array
(
    'LABEL_FIRST_NAME' => 'First Name',
    'LABEL_LAST_NAME' => 'Last Name',
    'LABEL_COMPANY_NAME' => 'Company'
)

The above is the detailed content of How to Get a List of Defined Constants in a PHP Class?. 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