Search code examples
phphacklang

Using Dynamic Variable Names to Call Static Variable in PHP


I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:

23    $level = $_SERVER['DEBUG_LEVEL'];
24    $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});

When I do this, the code fails with the error:

A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.

How would I use a specific Logger:: level in this way?

UPDATE:

I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.

However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.

The variable itself is declared here

PHP Version => 5.6.99-hhvm


Solution

  • So the answer was to use a function for a constant lookup:

    $handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));