使用PHP中的变量访问const [duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

让我用一个真实的例子来解释:

class Config{
 const DB_NAME = "FOO";
}

class ConfigLoader{
 public static function get($key) {
   return Config::$key;
 }
 public static function getTest() {
   return Config::DB_NAME;
 }
}

ConfigLoader::get("DB_NAME"); // return error: Access to undeclared static property

ConfigLoader::getTest(); // It's OK! return FOO

但我需要做一些像ConfigLoader :: get(“DB_NAME)方法

php oop
1个回答
0
投票

我没有找到访问类常量的直接方法。但是通过使用反射类,它是可能的。

class ConfigLoader
{
    public static function get($key)
    {
        return (new ReflectionClass('Config'))->getConstant('DB_NAME');
        // return (new ReflectionClass('Config'))->getConstants()['DB_NAME'];
    }

    public static function getTest()
    {
        return Config::DB_NAME;
    }
}


echo ConfigLoader::get('DB_NAME'); // return error: Access to undeclared static property

ReflectionClass课程报告有关课程的信息。 ReflectionClass::getConstant - 获取定义的常量 ReflectionClass::getConstants - 获取常量

产量

FOO

Demo

© www.soinside.com 2019 - 2024. All rights reserved.