mardi 17 septembre 2019

PHP: Accessing a class constant with a dynamic string value as name?

This is my enum:

abstract class Environment extends BasicEnum {
    const LOCAL = "LOCAL";
    const DEVELOPMENT = "DEVELOPMENT";
    const STAGING = "STAGING";
    const SANDBOX = "SANDBOX";
    const PRODUCTION = "PRODUCTION";
}

In some other class (a Twig extension) I do:

public function getCurrentEnv()
{
    $env = getenv("ENVIRONMENT");
    if($env !== false) {
        if(Environment::isValidName($env)) {
            $env = strtoupper($env);
            return Environment::$env;
        } else {
            throw new \Exception("The ENVIRONMENT variable should be defined correctly.");
        }
    }
}

The error is:

Access to undeclared static property: AppBundle\Twig\Extension\Enum\Environment::$env

I tried things like:

AppBundle\Twig\Extension\Enum\Environment::{$env}

But it seems like this is not working for constants. The value of $env is LOCAL and I know it is a defined constant, because I check it before.

What is the correct syntax to access a class constant with a dynamic string value being the name?





Aucun commentaire:

Enregistrer un commentaire