0

我正在尝试将 json 文件中的值分配给某种全局/静态变量,然后稍后在文件中使用该全局/静态变量。

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;
}
4

1 回答 1

2

这些年来,我的手指被全局变量烧了好几次,所以现在我用不同的方式做事。

为您的所有代码创建一个类以及一个run()方法,然后您可以为您的“全局”使用一个类属性。

像这样的东西:

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
   }
}

然后像这样调用它:

<?php
   $p = new myClass();
   $p->run();
于 2020-12-23T00:58:04.003 回答