【问题标题】:Unset referenced variable未设置引用变量
【发布时间】:2013-03-14 03:32:56
【问题描述】:

我创建了一个类来存储配置值。

我的 Config 类的代码:

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 不受影响。

【问题讨论】:

  • 不知道你为什么在这里这么多地使用引用。
  • 如果你使用例如 Config::get("website.forum.postsperpage") 类需要动态地获得 self::$params["website"]["forum"]["postperpage "]。这是管理动态嵌套数组的唯一方法(我认为)。

标签: php reference unset


【解决方案1】:

当您执行$ref = &$ref[$key]; 时,$ref 将保留$ref[$key](非引用),因此最好将unset() 应用于$ref[$key],这将取消其引用,例如这个:

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]);        
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2021-11-29
    相关资源
    最近更新 更多