0

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

Amir m
  • 13
  • 6
  • 1
    Possible duplicate of [Dynamic constant name in PHP](https://stackoverflow.com/questions/3995197/dynamic-constant-name-in-php) See static property usage in second answer. – Alex Andrei Apr 01 '19 at 09:34
  • https://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class Using Reflection maybe useful for you. – Sergey Bogdanov Apr 01 '19 at 09:43

1 Answers1

0

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.

Rahul
  • 18,271
  • 7
  • 41
  • 60