【问题标题】:php access self::VAR dynamically [duplicate]php动态访问self :: VAR [重复]
【发布时间】: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_1self::$id 尝试访问类(静态)属性$id。您可以将U_1U_2 组合成一个数组(将U_1U_2 作为键)并使用$id 作为该数组中的键来访问您需要的数据。或者您可以使用constant() 函数来访问其名称存储在字符串中的常量。

标签: php


【解决方案1】:

在顶层完成常量编译,您试图动态获取此常量,这就是您遇到问题的原因,您可以将其更改为静态变量以动态获取。

<?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);
?>

Live Demo

输出

Array
(
    [xxx] => A
)
Array
(
    [xxx] => B
)

另一种方法eval("return self::$id;");

    ............
    const U_1 = [
        'xxx' => 'A'
    ];

    const U_2 = [
        'xxx' => 'B'
    ];
    .............
    static function byId(string $id) {
        return eval("return self::$id;");
    }

Live Demo

【讨论】:

    【解决方案2】:

    self::U_1 尝试访问类常量U_1self::$id 尝试访问类(静态)属性$id

    您可以将U_1U_2 组合成一个数组(将U_1U_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];
        }
    }
    

    或者您可以使用constant() 函数来访问名称存储在字符串中的常量:

     class Dimensions extends Enum {
    
        const U_1 = [
            'xxx' => 'A'
        ];
    
        const U_2 = [
            'xxx' => 'B'
        ];
    
        static function byId(string $id) {
            return constant("self::$id");
        }
     }
    

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多