PHP - 创建一个类设置一个数组var并使用它全局

I need some help with a situation, that I have no ideea how to start with, not even where to look for.

I have a large *.ini file (for language) that I would want to parse only once at the start of a php document and then use the result anywhere in the document.

I think, I need a class, like:

class Language{
    private language = array();

    function get( $string ){
        return $this->language[ $string ];
    }

    function getLanguage(){
        /* get and parse *.ini file once */
        $result = array;

        /* set language */
        $this->language = $result;
    }
}

So, in theory, at php document beginning, the class, somehow, calls getLanguage() and set language array

Language::getLanguage();

And then, anywhere in the rest of php document, especially inside other classes (without sending as function param), get certaing language array element without parsing *.ini file again.

class AClass{
    function __construct(){
        echo Language::get( $certain_string );
    }
}
new AClass;

Any advice is well received.

Thanks.

To be able to call a method with :: you need to declare it static.

class Language {
    private static $lang = null; // you won't be able to get this directly
    public static function getLanguage(){
        if (self::$lang) { // you can check with is_null() or !is_array()
            return self::$lang; 
        }
        else { /* parse ini file here and set it in self::$lang */ }
    }
}
Language::getLanguage();

I think this is what you need. If you need further tuning, let me know.

PS: If you declare private function __construct(){} and private function __clone(){} - it will be a classic Singleton design pattern.

if you need to use Language::getLanguage(); you should define this function as static.

public static function getLanguage(){
        /* get and parse *.ini file once */
        $result = array;

        /* set language */
        $this->language = $result;
    }

But I recommend to use use "Singleton" pattern:

class Language{

    static private $_instance = null;

    private language = array();

    private function __construct(){}
    private function __clone(){}

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

    public function get( $string ){
        return $this->language[ $string ];
    }

    public function getLanguage(){
        /* get and parse *.ini file once */
        $result = array;

        /* set language */
        $this->language = $result;
    }
}

So using this you can call methods of this class like this:

Language::getInstance()->get('str');
Language::getInstance()->getLanguage();