php动态访问self::VAR
我想通过self访问类属性,但使用动态方法名: 而不是php动态访问self::VAR,php,Php,我想通过self访问类属性,但使用动态方法名: 而不是 self::U_1; 我需要像这样的东西: $id = 'U_1'; self::$id; 例如: class Dimensions extends Enum { const U_1 = [ 'xxx' => 'A' ]; const U_2 = [ 'xxx' => 'B' ]; st
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
作为此数组中的键来访问所需的数据:
class Dimensions extends Enum
{
const U = [
'U_1' => [
'xxx' => 'A'
],
'U_2' => [
'xxx' => 'B'
],
];
static function byId(string $id) {
return self::U[$id];
}
}
或者,您可以使用该函数访问名称存储在字符串中的常量:
class Dimensions extends Enum {
const U_1 = [
'xxx' => 'A'
];
const U_2 = [
'xxx' => 'B'
];
static function byId(string $id) {
return constant("self::$id");
}
}
常量编译在顶层完成,您试图动态获取该常量,这就是您遇到问题的原因,您可以将其更改为静态变量以动态获取
<?php
class Dimensions
{
public static $U_1 = [
'xxx' => 'A'
];
public static $U_2 = [
'xxx' => 'B'
];
static function all() {
$oClass = new ReflectionClass(__CLASS__);
return $oClass->getConstants();
}
static function byId(string $id) {
return self::${$id};
}
}
$obj = Dimensions::byId('U_1');
print_r($obj);
$obj = Dimensions::byId('U_2');
print_r($obj);
?>
另一种方法使用eval(“返回self::$id;”)代码>
self::U_1
尝试访问类常量U_1
,self::$id
尝试访问类(静态)属性$id
。您可以将U_1
和U_2
组合成一个数组(将U_1
和U_2
作为键),并使用$id
作为此数组中的键来访问所需的数据。也可以使用该函数访问名称存储在字符串中的常量。
Array
(
[xxx] => A
)
Array
(
[xxx] => B
)
............
const U_1 = [
'xxx' => 'A'
];
const U_2 = [
'xxx' => 'B'
];
.............
static function byId(string $id) {
return eval("return self::$id;");
}