【问题标题】:Unsetting Session by Reference does not work通过引用取消设置会话不起作用
【发布时间】:2019-09-02 17:09:22
【问题描述】:

我正在尝试使用函数取消设置会话,所以它更容易。 我这样调用函数:unsetSession("index1/index2/index3/...)

当我提供最后一个元素的完整路径时,它可以工作。但是,当我想删除包含更多元素的元素时,它不起作用。

例子:

$_SESSION

["test"]=>
array(1) {
  ["value1"]=>
  array(1) {
    ["value2"]=>
    string(6) "String"
  }
} 

这:unsetSession("test/value1/value2") 将起作用并删除 value2。 这:unsetSession("test/value1") 不会工作。那是我的问题。

代码:

PUBLIC function unsetSession($s) {

        if (!strstr($s, "/")) {

            unset($_SESSION[$s]);

        } 
        else {

            $temp = &$_SESSION;

            $path = explode('/', $s);

            if (!isset($temp[current($path)]) OR is_string($temp[current($path)])) return false;
            $temp = &$temp[current($path)];

            while ($next = next($path)) {

                if ((isset($temp[$next]) OR $temp[$next] == null) AND !is_array($temp[$next])) {

                    unset($temp[$next]);
                    return true;

                }

                $temp = &$temp[$next];

            }

            unset($temp); // <- DOES NOT UNSET SESSION, why?
            return true;

        }

        return false;

    }

知道为什么这不起作用吗?

【问题讨论】:

    标签: php session reference unset


    【解决方案1】:

    我将使用 current() 和 next() 替换提供数组最后一个元素的函数 end():

       function unsetSession($s) {
        if (!strstr($s, "/")) {
            unset($_SESSION[$s]);
        } else {
            $path = explode('/', $s)
            unset(end($path));
        }
        return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 2016-07-06
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 2017-03-23
      相关资源
      最近更新 更多