Home > Backend Development > PHP Tutorial > How to Access Class Constants Dynamically in PHP?

How to Access Class Constants Dynamically in PHP?

Linda Hamilton
Release: 2024-11-04 07:16:31
Original
434 people have browsed it

How to Access Class Constants Dynamically in PHP?

Accessing Class Constants Dynamically

Accessing class constants can be a challenge when you only know the constant's name during runtime. By utilizing system functions or reflection, it's possible to overcome this limitation.

Using Constant Function

The constant function simplifies constant retrieval. It's capable of working with both constants defined using define and class constants:

<code class="php">class A
{
    const MY_CONST = 'myval';

    static function test()
    {
        $c = 'MY_CONST';
        return constant('self::'. $c);
    }
}

echo A::test(); // Output: myval</code>
Copy after login

Using Reflection Class

For a more elaborate approach, reflection can be employed:

<code class="php">$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // Output: myval</code>
Copy after login

The above is the detailed content of How to Access Class Constants Dynamically in PHP?. 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