Dynamic constant name in PHP
Asked Answered
T

4

89

I am trying to create a constant name dynamically and then get at the value.

define( CONSTANT_1 , "Some value" ) ;

// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;

// try to assign the constant value to a variable...
$constant_value = $constant_name;

But I find that $constant value still contains the NAME of the constant, and not the VALUE.

I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.

Can somebody throw some light on this?

Tammy answered 22/10, 2010 at 8:44 Comment(0)
A
169

http://dk.php.net/manual/en/function.constant.php

echo constant($constant_name);
Alcoholic answered 22/10, 2010 at 8:46 Comment(0)
D
88

And to demonstrate that this works with class constants too:

class Joshua {
    const SAY_HELLO = "Hello, World";
}

$command = "HELLO";
echo constant("Joshua::SAY_$command");
Dougald answered 27/2, 2013 at 20:10 Comment(4)
Worth noting that you may need to specify the fully qualified (namespaced) class name if the constant is in a class which is not in the current namespace - regardless of if you have added a "use" for the class in your file.Perseverance
This answer is great because of good example. That's exactly what I was looking for :) Thanks!Verbenia
@Perseverance The ::class constant can be used to retrieve the fully qualified namespace, for example: constant(YourClass::class . '::CONSTANT_' . $yourVariable);Shipboard
Note that the ::class keyword is available since php 5.5Neo
R
9

To use dynamic constant names in your class you can use reflection feature (since php5):

$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);

For example: if you want to filter only specific (SORT_*) constants in the class

class MyClass 
{
    const SORT_RELEVANCE = 1;
    const SORT_STARTDATE = 2;

    const DISTANCE_DEFAULT = 20;

    public static function getAvailableSortDirections()
    {
        $thisClass = new ReflectionClass(__CLASS__);
        $classConstants = array_keys($thisClass->getConstants());

        $sortDirections = [];
        foreach ($classConstants as $constName) {
            if (0 === strpos($constName, 'SORT_')) {
                $sortDirections[] =  $thisClass->getConstant($constName);
            }
        }

        return $sortDirections;
    }
}

var_dump(MyClass::getAvailableSortDirections());

result:

array (size=2)
  0 => int 1
  1 => int 2
Rostov answered 18/2, 2015 at 11:38 Comment(0)
A
0

Maybe ugly but it work :

<?php

$one = '1';

$CONSTS = array( 'VALUE_'.$one => 36, 'NAME' => 'paul' );
    
foreach( $CONSTS as $key => $value ){
        
    define( $key, $value );
}

// note: .PHP_EOL is a line break like: ."\r\n";
echo VALUE_1.PHP_EOL; 

echo NAME.PHP_EOL;

// output :
36
paul
?>

Yes ... Shame on me !

Avulsion answered 10/7 at 3:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.