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

使用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.

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

报告相同问题?

悬赏问题

  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥60 GFSK两点调制锁相环simulink模型
  • ¥20 双非跨考工科哪个专业和方向就业前景好?
  • ¥20 求会6sv辐射传输模型,辅导(可py6s🙏🏻有偿
  • ¥15 .xla后缀的文件拖到excel里什么内容也没有怎么办
  • ¥20 Workbench中Mechanical打不开、闪退是什么原因?
  • ¥240 MapReduce应用实践 学生课程
  • ¥15 hlss视频显示AUTHORITY_INVALID
  • ¥15 MAX9296A+MAX96717,美信gmsl解串有人做过吗?
  • ¥15 求帮我解决一下inode 爆满的问题(有偿)