PHPer 們可能都知道 list 的用法,簡單來說就是可以在一個表達試里通過數組對多個變量賦值:
- $values = array('value1', 'value2');
- $list($v1, $v2) = $values;
感覺是不是很方便呢?在 PHP 7.1 中,還能更省事兒:
[$v1, $v2] = ['foo', 'bar'];
這還不是最給力的,在 PHP 7.1 里我們還可以指定鍵值來賦值,從而不用關心數組元素的順序:
- list('v1' => $value1, 'v2' => $value2) = array('v1' => 'foo', 'v2' => 'bar', ...);
- // or
- ['v1' => $value1, 'v2' => $value2] = ['v1' => 'foo', 'v2' => 'bar', ...];
其實在 PHP 5 的年代,list 就有一個很不錯的用法可能大家都不熟悉:
- $arr = [
- ['x', 'y'],
- ['x1', 'y2'],
- ];
- foreach ($arr as list($x, $y)) {
- echo $x, ' ', $y, PHP_EOL;
- }
到了 PHP 7.1,因為可以指定鍵值賦值,這種用法將更加的靈活,估計也更加常用:
- $arr = [
- ['x' => 1, 'y' => '2'],
- ['x' => 2, 'y' => '4'],
- ];
- foreach ($arr as ['x' => $x, => $y)) {
- echo $x, ' ', $y, PHP_EOL;
- }
再看看一個官網的例子,是不是感覺好像春風拂面一樣清爽:
- class ElePHPant
- {
- private $name, $colour, $age, $cuteness;
- public function __construct(array $attributes) {
- // $this->name = $attributes['name']; // 以前
- // 現在
- [
- "name" => $this->name,
- "colour" => $this->colour,
- "age" => $this->age,
- "cuteness" => $this->cuteness
- ] = $attributes;
- } //Vevb.com
- // ...
- }
值得一提的是:此種賦值方式,是可以嵌套使用的!
[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
最后,在 PHP 7.1 的提案里有一個展望,也非常值得期待:
- class ElePHPant
- {
- private $name, $colour, $age, $cuteness;
- public function __construct(["name" => string $name, "colour" => /Colour $colour, "age" => int $age, "cuteness" => float $cuteness]) {
- $this->name = $name;
- $this->colour = $colour;
- $this->age = $age;
- $this->cuteness = $cuteness;
- }
- // ...
- }
如果 PHP 推出此語法,那么參數列表將不再關心參數順序,PHP 的小伙伴將不再羨慕 Ruby 的小伙伴啦!
新聞熱點
疑難解答