Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php动态访问self::VAR_Php - Fatal编程技术网

php动态访问self::VAR

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访问类属性,但使用动态方法名:

而不是

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;");
    }