douyi6755 2018-01-28 19:24
浏览 6
已采纳

在作业之前是否未设置?

class RouteCollection implements \IteratorAggregate, \Countable
{
    /**
     * @var Route[]
     */
    private $routes = array();

    public function add($name, Route $route)
    {
        unset($this->routes[$name]);

        $this->routes[$name] = $route;
    }

     public function remove($name)
     {
        foreach ((array) $name as $n) {
            unset($this->routes[$n]);
        }
     }
}

This is a piece of code from the class Symfony\Component\Routing\RouteCollection. Does unset before the assignment matter?

Why is it done?

Second question: Why in remove method simple string is parsed to array?

Why I can't use simply:

unset($this->routes[$name]);

Same as in add method?

  • 写回答

1条回答 默认 最新

  • dooid3005 2018-01-28 19:46
    关注

    Does unset before the assignment matter?

    It can. If $this->routes[$name] is a PHP reference and you don't use unset, all symbols pointing to the underlying value will point to the new value. If you use unset before, the assignment will only affect the symbol used.

    Second question: Why in remove method simple string is parsed to array?

    This is just a small trick that allows you to use the remove method with both strings and array. When you cast a string (e.g. 'abc') to an array, PHP will return an array that contains the string as its only value (array(0 => 'abc')). For strings the method works as you suggested, and for arrays it will unset all names in the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入