静态函数中包含文件中的全局变量

Global variable from included file in static function

我有 index.php 和用于翻译短语的包含文件 strings.php。在 strings.php 中包含基于用户语言的文件:$lang.php。此 $lang.php 文件是从 $lang.ini 自动生成的,包含单个数组:

  <?php $translation = array (
      'USER_PROFILE' => 'Uživatelský profil',
      'MESSAGES' => 'Zprávy',
      'NOTIFICATIONS' => 'Oznámení',
      'SETTINGS' => 'Nastavení',
      ...

class Strings with static function and global assigned array $translation from $lang.phpstrings.php:

include_once('cache/'.$lang.'.php');

class Strings {
    static public function translate($string) {
        global $translation;
        ...
    }
}

但是 $translation in translate() function returns null 在这种情况下。如果我在 index.php 中包含 $lang.php 它突然起作用,但是如果我调用 Strings:其他文件中的 :translate() 函数,$translation 再次 returns 无效。我不明白这种行为。 (对不起英语)

由于包含文件 $lang.php 的方式,变量 $translation 在函数中作为局部变量而不是方法 Strings::translate() 中的 global 变量期待它。

在我们聊天讨论并且我理解了问题之后,我可以提出两个解决方案:

解决方案 1(快速解决方法)

更改文件 $lang.php:

<?php global $translation = array (
    'USER_PROFILE' => 'Uživatelský profil',
    ...

这样,变量 $translation 就在全局上下文中创建,一切都按预期工作。

解决方案 2(更好的设计)

限制变量的范围$translation

文件$lang.php:

<?php return array (
    'USER_PROFILE' => 'Uživatelský profil',
    ...

这样就不会创建任何变量(既不是本地变量也不是全局变量),这消除了混淆的根源。

文件strings.php:

class Strings {

    static $translation;

    static private function initialize() {
         global $lang;
         static::$translation = include_once('cache/'.$lang.'.php');
    }

    static public function translate($string) {
        if (! isset(static::$translation)) {
            static::initialize();
        }

        // use static::$translation instead of global $translation
    }
}

方案三(正确设计)

一个更好的设计(实际上是正确的设计)是制作方法 initialize() public,将 $lang 更改为它的参数并在您的代码中尽快调用它您确定了 $lang.

的值

文件strings.php:

class Strings {

    static $translation;

    // Call this method once, as soon as you determined what
    // language you need to use
    static public function initialize($lang) {
         static::$translation = include_once('cache/'.$lang.'.php');
    }

    static public function translate($string) {
        // use static::$translation instead of global $translation
    }
}