0
我創建了一個類來存儲配置值。未設置引用變量
我的配置類的代碼:
class Config
{
protected static $params = array();
protected static $instance;
private function __construct(array $params=NULL){
if(!empty($params)){
self::$params = $params;
}
}
public static function init(array $params=NULL){
if(!isset(self::$instance))
self::$instance = new Config($params);
}
public static function getInstance(){
return self::$instance;
}
public static function initialized(){
return isset(self::$instance);
}
public static function get($name)
{
$ref = &self::$params;
$keys = explode('.', $name);
foreach ($keys as $idx => $key):
if (!is_array($ref) || !array_key_exists($key, $ref))
return NULL;
$ref = &$ref[$key];
endforeach;
return $ref;
}
public function delete($name){
$ref = &self::$params;
$keys = explode('.', $name);
foreach ($keys as $idx => $key):
if (!is_array($ref) || !array_key_exists($key, $ref))
return NULL;
$ref = &$ref[$key];
endforeach;
unset($ref);
}
public function set($name, $value) {
$ref = &self::$params;
$keys = explode('.', $name);
foreach ($keys as $idx => $key) {
if (!is_array($ref)) {
return false;
throw new Exception('key "'.implode('.', array_slice($keys, 0, $idx)).'" is not an array but '.gettype($ref));
}
if (!array_key_exists($key, $ref)) {
$ref[$key] = array();
}
$ref = &$ref[$key];
}
$ref = $value;
return true;
}
public function getAll(){
return self::$params;
}
public function clear(){
self::$params = array();
}
}
配置方法採用的是點陣格式:
Config::set("test.item","testdrive"); //store in class, array["test"]["item"]="testdrive"
但是,即時通訊試圖建立一個方法來刪除值,例如:
Config::delete("test.item");
在get和set方法中,我使用引用變量來查找正確的項目,但我不知道如何刪除引用的變量。如果我使用unset($ref)
,則Config::$params
不受影響。
不知道爲什麼你正在使用這裏引用如此之多。 – 2013-03-24 17:21:54
如果你使用例如Config :: get(「website.forum.postsperpage」),該類需要獲得dinamically self :: $ params [「website」] [「forum」] [「postperpage」]。它是管理嵌套數組的唯一方式(我認爲)。 – 2013-03-24 17:25:39