【发布时间】:2018-04-05 08:42:46
【问题描述】:
我想通过 self 访问一个类属性,但使用的是动态方法名:
而不是
self::U_1;
我需要类似的东西:
$id = 'U_1';
self::$id;
例子:
class Dimensions extends Enum
{
const U_1 = [
'xxx' => 'A'
];
const U_2 = [
'xxx' => 'B'
];
static function all() {
$oClass = new ReflectionClass(__CLASS__);
return $oClass->getConstants();
}
static function byId(string $id) {
return self::$id
}
}
【问题讨论】:
-
self::U_1尝试访问类常量U_1,self::$id尝试访问类(静态)属性$id。您可以将U_1和U_2组合成一个数组(将U_1和U_2作为键)并使用$id作为该数组中的键来访问您需要的数据。或者您可以使用constant()函数来访问其名称存储在字符串中的常量。
标签: php