我尝试动态创建一个常量名称,然后获取该值。
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;
但是我发现$constant值仍然包含常量的名称,而不是值。
我也尝试了第二级间接$$constant_name
,但这会使它成为一个变量,而不是常量。
有没有人能解释一下这个?
发布于 2010-10-22 16:46:06
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
发布于 2013-02-28 04:10:09
为了演示这也适用于类常量:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
发布于 2015-02-18 19:38:16
要在类中使用动态常量名称,可以使用反射功能(从php5开始):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
例如:如果只想过滤类中的特定(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());
结果:
array (size=2)
0 => int 1
1 => int 2
https://stackoverflow.com/questions/3995197
复制相似问题