Phper may all know the use of lists, simply by assigning values to multiple variables through an array in an expression test:
$values = Array (' value1 ', ' value2 ');
$list ($v 1, $v 2) = $values;
Does it feel convenient? In PHP 7.1, it can be more convenient:
[$v 1, $v 2] = [' foo ', ' Bar '];
This is not the most empowering, in PHP 7.1 We can also specify key values to assign values so that we do not care about the order of the array elements:
List (' v1 ' => $value 1, ' v2 ' => $value 2) = Array (' v1 ' => ' foo ', ' v2 ' => ' Bar ', ...);
Or
[' v1 ' => $value 1, ' v2 ' => $value 2] = [' v1 ' => ' foo ', ' v2 ' => ' Bar ', ...];
In fact, in the PHP 5 era, the list has a very good usage may not everyone familiar with:
$arr = [
[' x ', ' Y '],
[' X1 ', ' y2 '],
];
foreach ($arr as List ($x, $y)) {
Echo $x, ', $y, Php_eol;
}
To PHP 7.1, because you can specify key value assignments, this usage will be more flexible and more commonly estimated:
$arr = [
[' X ' => 1, ' Y ' => ' 2 '],
[' X ' => 2, ' y ' => ' 4 '],
];
foreach ($arr as [' X ' => $x, ' y ' => $y)) {
Echo $x, ', $y, Php_eol;
}
Take a look at an official website example, is not feeling as refreshing as the Spring Breeze:
Class Elephpant
{
private $name, $colour, $age, $cuteness;
& nbsp Public function __construct (array $attributes) {
//$this->name = $ attributes[' name ']; Previous
/Now
[
] Name "=> $this->name,
" colour "=> $ This->colour,
"age" => $this->age,
"cuteness" => $this->cuteness
] = $attributes;
}
//...
}
It is worth mentioning: this kind of assignment method, can be nested use!
[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
Finally, there is a vision in the PHP 7.1 proposal, and it is well worth looking forward to:
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;
}
// ...
}
If PHP introduced this syntax, then the parameter list will no longer care about the parameter order, PHP's small partner will no longer envy Ruby's little buddy!