0

I have the following warning notice from my functions.php file:

Warning: Use of undefined constant ENVIRONMENT - assumed 'ENVIRONMENT' (this will throw an Error in a future version of PHP)

This is the code in my functions.php:

$dist_dir = get_theme_root_uri() . "/" . wp_get_theme() . "/dist";

/* environement */
// Set your environment/url pairs
$environments = array(
    'local' => 'local.mysite.com',
    'staging' => 'staging.mysite.com',
    'production' => 'mysite.com'
);

// Get the hostname
$http_host = $_SERVER['HTTP_HOST'];
// Loop through $environments to see if there’s a match
foreach ($environments as $environment => $hostname) {
    //echo $hostname . " www";
    if (stripos($http_host, $hostname) !== false) {
        define('ENVIRONMENT', $environment);
        break;
    }
}

if (ENVIRONMENT == 'local') {
    define('ASSETSDIR', get_template_directory_uri() . '/assets');
} else {
    define('ASSETSDIR', $dist_dir . '/assets');
}

The line in relation with the notice is this one:

if (ENVIRONMENT == 'local') {

I'm not sure to understand why there is this warning notice and how to solve it.

Thank you.

3
  • 1
    Are you 100% sure that the hostnames in the $environments array are correct and free of typos? Also, you could change your if() to explicitly check that ENVIRONMENT is defined: if ( defined( 'ENVIRONMENT' ) && 'local' === ENVIRONMENT ) { ... }.
    – Pat J
    Commented Jan 2, 2023 at 19:37
  • Thank you @PatJ. I modified the if() to check if the constant is defined as you mentioned and the warning disappeared. Commented Jan 3, 2023 at 10:08
  • @PatJ I let you post your comment above as the solution, thanks. Commented Jan 3, 2023 at 18:03

1 Answer 1

1

It's possible that your $http_host isn't in the list of possible choices. You can always check first that the ENVIRONMENT constant has actually been defined:

if ( defined( 'ENVIRONMENT' ) && 'local' === ENVIRONMENT ) { 
     define('ASSETSDIR', get_template_directory_uri() . '/assets');
} else {
    define('ASSETSDIR', $dist_dir . '/assets');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.