一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-24 16:42:02 编辑:袖梨 来源:一聚教程网


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' => $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;
    }
 
    // ...
}

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

[[$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 的小伙伴啦!

热门栏目