Home > Backend Development > PHP Tutorial > Can I Access Class Constant Values Dynamically Using a Variable?

Can I Access Class Constant Values Dynamically Using a Variable?

Barbara Streisand
Release: 2024-11-04 03:17:02
Original
966 people have browsed it

Can I Access Class Constant Values Dynamically Using a Variable?

Getting Class Constant Values Dynamically

Question:

Is it possible to access the value of a class constant dynamically using a variable that contains the constant's name?

Answer:

Yes, there are two methods to achieve this: using the constant function or reflection.

Method 1: Constant Function

The constant function can be used to retrieve the value of both user-defined constants declared with 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(); // outputs "myval"</code>
Copy after login

Method 2: Reflection Class

A more comprehensive approach is to use reflection:

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

The above is the detailed content of Can I Access Class Constant Values Dynamically Using a Variable?. 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