你能否详细解释为什么这段代码:
$arr = array(1, 2, 3);
list($result[], $result[], $result[]) = $arr;
print_r($result);
结果是:
Array ( [0] => 3 [1] => 2 [2] => 1 )
?
解决方法:
list() assigns the values starting with the right-most parameter. If you are using plain variables, you don’t have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn’t. It’s assigned in the reverse order.
如果你想知道为什么会这样做,那么原因可能是,使用LALR(1)解析器更容易实现从右到左的赋值,在这里你通常只使用左手边递归,这是出于性能原因:
assignment_list:
assignment_list ',' assignment_list_element
| assignment_list_element
;
assignment_list_element:
variable { zend_do_add_list_element(&$1 TSrmlS_CC); }
| T_LIST '(' { zend_do_new_list_begin(TSrmlS_C); } assignment_list ')' { zend_do_new_list_end(TSrmlS_C); }
| /* empty */ { zend_do_add_list_element(NULL TSrmlS_CC); }
;