Php 未设置引用变量
我创建了一个类来存储配置值 我的配置类的代码:Php 未设置引用变量,php,reference,unset,Php,Reference,Unset,我创建了一个类来存储配置值 我的配置类的代码: 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(a
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)
,配置::$params
不受影响。当您使用$ref=&$ref[$key]
然后$ref
将保存$ref[$key]
的值(非ref),因此最好在$ref[$key]
上应用unset()
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;
endforeach;
unset($ref[$key]);
}
不知道你为什么在这里这么多地使用引用。如果你使用例如Config::get(“website.forum.postsperpage”),那么类需要以友好的方式获得自己的::$params[“website”][“forum”][“posterpage”]。我认为这是管理嵌套数组的唯一方法。