【问题标题】:Default value for array destruction operation in PHP 7.1PHP 7.1 中数组销毁操作的默认值
【发布时间】:2018-02-07 03:47:23
【问题描述】:

有没有办法为没有指定索引的已破坏数组设置默认值?

类似于 ES6 中的破坏对象,如果传递的对象没有属性(在下面的例子中,name 属性),它将有一个默认值:

const ({name = '', age}) => {
};

我目前正在销毁如下数组:

// Inside my class
public function __construct(array $props) {
    [ 'id' => $this->id, 'name' => $this->name ] = $props;
}

但是,我希望'id' 是可选的,这样$this->id 可以在没有传递'id' 时将0 作为默认值。

【问题讨论】:

  • 您不能分配给数组[ 'id' => $this->id, 'name' => $this->name ]。您只能为变量赋值。
  • 我没有为数组赋值,我正在破坏数组将它的值赋给我的类属性

标签: php-7 php-7.1


【解决方案1】:

这对我有用:

<?php

class Ciao
{
    private $id = 666;

    public function __construct(array $props) {
        $props['id'] = $props['id'] ?? 666;
        [ 'id' => $this->id, 'name' => $this->name ] = $props;
    }
}


$ciao = new Ciao([
    'id' => 42,
    'name' => 'ciao',
]);
// $ciao::$id == 42


$ciao = new Ciao([
    'name' => 'ciao',
]);
// $ciao::$id == 666

【讨论】:

  • 反过来,我是在破坏一个数组,而不是在构造
  • @ChristopherFrancisco 谢谢。我发现了使用数组的新方法……非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 2017-11-29
  • 2019-02-05
相关资源
最近更新 更多