我需要一些帮助,我不知道如何开始,甚至不知道去哪里找。
我有一个大的*.ini文件(用于语言),我只想在php文档的开始处解析一次,然后在文档的任何地方使用结果。
我想,我需要一个类,像:
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;
}
}
理论上,在php文档开头,类会调用getLanguage()并设置语言数组
Language::getLanguage();
然后,在php文档的其他任何地方,特别是在其他类中(不作为函数参数发送),获得特定的语言数组元素,而无需再次解析*.ini文件。
class AClass{
function __construct(){
echo Language::get( $certain_string );
}
}
new AClass;
任何建议我们都欢迎。
谢谢。
要用::来调用一个方法,你需要将它声明为静态。
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();
我想这就是你需要的。如果您需要进一步调优,请告诉我。
PS:如果你声明private function __construct(){}
和private function __clone(){}
-它将是一个经典的单例设计模式
如果需要使用Language::getLanguage();你应该把这个函数定义为静态的。
public static function getLanguage(){
/* get and parse *.ini file once */
$result = array;
/* set language */
$this->language = $result;
}
但是我推荐使用use "Singleton"模式:
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;
}
}
使用这个你可以像这样调用这个类的方法:
Language::getInstance()->get('str');
Language::getInstance()->getLanguage();