What are the advantages of encapsulating configuration and ID values in classes or singletons rather than manipulating global arrays like $_SERVER or $_ENV?

Encapsulating configuration and ID values in classes or singletons rather than manipulating global arrays like $_SERVER or $_ENV provides better organization, encapsulation, and control over the data. It helps in avoiding naming conflicts and accidental modifications of global variables. Additionally, using classes or singletons allows for easier testing and maintenance of the code.

<?php

class Config {
    private static $instance;
    private $configValues = [];

    private function __construct() {
        $this->configValues['db_host'] = 'localhost';
        $this->configValues['db_user'] = 'root';
        $this->configValues['db_pass'] = 'password';
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function getConfigValue($key) {
        return $this->configValues[$key] ?? null;
    }
}

$config = Config::getInstance();
echo $config->getConfigValue('db_host'); // Output: localhost