php - Get config value to a global or const variable

I'm trying to assign a value from json file to a some kind of global / static variable and then use that global / static variable later down the file.

static $API_KEY = get_api_key(); // gives: Constant expression contains invalid operations
define('API_KEY', get_api_key()); // gives: PHP Notice:  Undefined variable: API_KEY in /content.php on line 422

function get_api_key() {
    $file_content = file_get_contents("./msx/start.json");
    $json = json_decode($file_content);
    
    return $json->tmdb_api_key;
}

Answer

Solution:

I've had my fingers burned by global variables several times over the years, so now I do things a different way.

Create a class for all your code, along with a run() method, and then you can use a class property for your 'global'.

Something like this:

class myClass {
    private $apiKey;

    public function __construct() {
        $this->apiKey = $this->getApiKey();
    }

    private function getApiKey() {
        $file_content = file_get_contents("./msx/start.json");
        $json = json_decode($file_content);

        return $json->tmdb_api_key;
   }

   public function run() {
   // do stuff using $this->apiKey
   }
}

And then invoke it like this:

<?php
   $p = new myClass();
   $p->run();

Source