


Can I Access Class Constant Values Dynamically Using a Variable?
Nov 04, 2024 am 03:17 AMGetting 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>
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>
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
