PHP 中的动态常量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3995197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic constant name in PHP
提问by vikmalhotra
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.
但我发现 $constant 值仍然包含常量的 NAME,而不是 VALUE。
I tried the second level of indirection as well $$constant_name
But that would make it a variable not a constant.
我也尝试了第二级间接$$constant_name
但这会使它成为一个变量而不是一个常量。
Can somebody throw some light on this?
有人可以对此有所了解吗?
回答by Mads Lee Jensen
http://dk.php.net/manual/en/function.constant.php
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
回答by DonVaughn
And to demonstrate that this works with class constants too:
并证明这也适用于类常量:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
回答by Dado
To use dynamic constant names in your class you can use reflection feature (since php5):
要在类中使用动态常量名称,您可以使用反射功能(自 php5 起):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
For example: if you want to filter only specific (SORT_*) constants in the class
例如:如果您只想过滤类中的特定 (SORT_*) 常量
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