【发布时间】: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 ]。您只能为变量赋值。 -
我没有为数组赋值,我正在破坏数组将它的值赋给我的类属性