vik*_*tra 72 php constants indirection
我试图动态创建一个常量名称,然后获取该值.
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;
Run Code Online (Sandbox Code Playgroud)
但是我发现$ constant值仍然包含常量的NAME,而不是VALUE.
我也尝试了第二级间接$$constant_name
但是这会使它变量而不是常量.
有人可以对此有所了解吗?
Mad*_*sen 139
http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);
Run Code Online (Sandbox Code Playgroud)
Don*_*ghn 60
并证明这也适用于类常量:
class Joshua {
const SAY_HELLO = "Hello, World";
}
$command = "HELLO";
echo constant("Joshua::SAY_$command");
Run Code Online (Sandbox Code Playgroud)
要在类中使用动态常量名称,可以使用反射功能(因为php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
Run Code Online (Sandbox Code Playgroud)
例如:如果要仅过滤类中的特定(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());
Run Code Online (Sandbox Code Playgroud)
结果:
array (size=2)
0 => int 1
1 => int 2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36795 次 |
最近记录: |