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?
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.