Search code examples
phpenvironment-variablesapache2defined

Strange behaviour of PHP defined()


I have set an env var SetEnv YII_ENV prod in apache vhost file, because I have the following line in my project:

defined('YII_ENV') or define('YII_ENV', 'dev');

The problem is that defined() behaves really weird. I have tried the following code:

echo getenv('YII_ENV');
echo '<br>';
var_dump(defined('YII_ENV'));

The result:

prod
bool(false)

I can echo the value of the var, but the defined() returns false. I know I can rewrite the condition, but I am really curious why this is happening.


Solution

  • Explanation - defined function

    Checks whether a given named constant exists

    So, defined('YII_ENV') checks whether constant YII_ENV is defined.

    But environment variable with same name YII_ENV is not a constant, it's another entity.

    That's why you get your output, which is totally correct.