dqqt31923 2019-04-01 09:31
浏览 92
已采纳

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

This question already has an answer here:

Let me explain with a real example:

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

But i need to do something like ConfigLoader::get("DB_NAME) method

</div>
  • 写回答

1条回答 默认 最新

  • duangou1551 2019-04-01 09:46
    关注

    I ain't found a direct way to access constants of class. But by using reflection class it's possible.

    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
    

    The ReflectionClass class reports information about a class.
    ReflectionClass::getConstant — Gets defined constant
    ReflectionClass::getConstants — Gets constants

    Output

    FOO
    

    Demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 qt+ffmpeg报错non-existing PPS 0 referenced
  • ¥15 FOC simulink
  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?