我需要一些情况帮助,我不知道如何开始,甚至不在哪里寻找。
我有一个大的* .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文档的其余部分的任何地方,特别是在其他类中(不作为函数param发送),获取certaing语言数组元素而不再解析* .ini文件。
class AClass{
function __construct(){
echo Language::get( $certain_string );
}
}
new AClass;
任何建议都很受欢迎。
感谢。
答案 0 :(得分:1)
为了能够用::调用方法,你需要将它声明为静态。
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(){}
- 它将是经典的Singleton design pattern。
答案 1 :(得分:1)
如果你需要使用Language :: getLanguage();你应该把这个函数定义为static。
public static function getLanguage(){
/* get and parse *.ini file once */
$result = array;
/* set language */
$this->language = $result;
}
但我建议使用“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();