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

Susan Sarandon
Release: 2024-11-17 11:01:02
Original
793 people have browsed it

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());
Copy after login

Output:

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

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!

source:php.cn
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