首页 > 语言 > PHP > 正文

PHP 7.1 方括号数组符号多值复制和指定键值赋值

2024-09-04 11:46:40
字体:大 中 小
来源:转载
供稿:网友

PHPer 们可能都知道 list 的用法,简单来说就是可以在一个表达试里通过数组对多个变量赋值:

  1. $values = array('value1', 'value2'); 
  2. $list($v1, $v2) = $values; 

感觉是不是很方便呢?在 PHP 7.1 中,还能更省事儿:

[$v1, $v2] = ['foo', 'bar'];

这还不是最给力的,在 PHP 7.1 里我们还可以指定键值来赋值,从而不用关心数组元素的顺序:

  1. list('v1' => $value1, 'v2' => $value2) = array('v1' => 'foo', 'v2' => 'bar', ...); 
  2. // or 
  3. ['v1' => $value1, 'v2' => $value2] = ['v1' => 'foo', 'v2' => 'bar', ...]; 

其实在 PHP 5 的年代,list 就有一个很不错的用法可能大家都不熟悉:

  1. $arr = [ 
  2.     ['x', 'y'], 
  3.     ['x1', 'y2'], 
  4. ]; 
  5.  
  6. foreach ($arr as list($x, $y)) { 
  7.     echo $x, ' ', $y, PHP_EOL; 
  8. } 

到了 PHP 7.1,因为可以指定键值赋值,这种用法将更加的灵活,估计也更加常用:

  1. $arr = [ 
  2.     ['x' => 1, 'y' => '2'], 
  3.     ['x' => 2, 'y' => '4'], 
  4. ]; 
  5.  
  6. foreach ($arr as ['x' => $x, 'y' => $y)) { 
  7.     echo $x, ' ', $y, PHP_EOL; 
  8. } 

再看看一个官网的例子,是不是感觉好像春风拂面一样清爽:

  1. class ElePHPant 
  2. { 
  3.     private $name, $colour, $age, $cuteness; 
  4.  
  5.     public function __construct(array $attributes) { 
  6.         // $this->name = $attributes['name']; // 以前 
  7.          
  8.         // 现在 
  9.         [ 
  10.             "name" => $this->name, 
  11.             "colour" => $this->colour, 
  12.             "age" => $this->age, 
  13.             "cuteness" => $this->cuteness 
  14.         ] = $attributes; 
  15.     } //Vevb.com 
  16.  
  17.     // ... 
  18. } 

值得一提的是:此种赋值方式,是可以嵌套使用的!

[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];

最后,在 PHP 7.1 的提案里有一个展望,也非常值得期待:

  1. class ElePHPant 
  2. { 
  3.     private $name, $colour, $age, $cuteness; 
  4.  
  5.     public function __construct(["name" => string $name, "colour" => /Colour $colour, "age" => int $age, "cuteness" => float $cuteness]) { 
  6.         $this->name = $name; 
  7.         $this->colour = $colour; 
  8.         $this->age = $age; 
  9.         $this->cuteness = $cuteness; 
  10.     } 
  11.  
  12.     // ... 
  13. } 

如果 PHP 推出此语法,那么参数列表将不再关心参数顺序,PHP 的小伙伴将不再羡慕 Ruby 的小伙伴啦!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表