代码之家  ›  专栏  ›  技术社区  ›  onassar

取消设置php引用

  •  2
  • onassar  · 技术社区  · 15 年前

    所以我有了这个函数,它返回一个对传入数组的特定点的引用。我想调用unset,然后将结果从数组/引用中移除,但是调用unset只移除引用,而不是原始数组中的数据。有什么想法吗?

    3 回复  |  直到 15 年前
        1
  •  4
  •   zombat    15 年前

    将引用设置为 null 将销毁引用(和任何其他引用)链接到的数据。

    Unsetting References 在手册中了解更多信息。基本上你想做以下事情(摘自评论):

    $a = 1;
    $b =& $a;
    $c =& $b;  //$a, $b, $c reference the same content '1'
    
    $b = null; //All variables $a, $b or $c are unset
    

    在你的情况下,它看起来像这样:

    $a =& getArrayReference($whatever);
    $a = null;
    

    编辑

    若要清除任何误解,请在取消设置数组引用时执行以下操作:

    $arr = array('x','y','z');
    
    $x =& $arr[1];
    unset($x);
    print_r($arr);
    //gives Array ( [0] => x [1] => y [2] => z )
    
    $x =& $arr[1];
    $x = null;
    print_r($arr);
    //gives Array ( [0] => x [1] => [2] => z ) 
    

    注意第二个数组索引在第一个示例中没有删除它的内容 unset() ,但将引用设置为 无效的 完成这个。

    注意:如果您还需要取消设置数组索引,我不太清楚您是否需要这样做,那么您需要找到一种方法来引用数组的键而不是值,可能是通过更改函数的返回值。

        2
  •  1
  •   Rune Kaagaard    15 年前

    预期的行为是取消设置引用不会取消正在被引用的变量。一种解决方案是返回键而不是值,并使用它来取消设置原始值。

        3
  •  0
  •   outis    15 年前

    注意 unset on references 是故意的。相反,您可以返回要删除的元素的索引,或者返回一个索引数组(如果数组不是平面的)。

    例如,可以使用以下函数:

    function delItem(&$array, $indices) {
        $tmp =& $array;
        for ($i=0; $i < count($indices)-1; ++$i) {
            $key = $indices[$i];
            if (isset($tmp[$key])) {
                $tmp =& $tmp[$key];
            } else {
                return array_slice($indices, 0, $i+1);
            }
        }
        unset($tmp[$indices[$i]]);
        return False;
    }
    

    或者,如果你喜欢例外,

    function delItem(&$array, $indices) {
        $tmp =& $array;
        while (count($indices) > 1) {
            $i = array_shift($indices);
            if (isset($tmp[$i])) {
                $tmp =& $tmp[$i];
            } else {
                throw new RangeException("Index '$i' doesn't exist in array.");
            }
        }
        unset($tmp[$indices[0]]);
    }