Default value for array destruction operation in PHP 7.1

900 Views Asked by At

Is there any way to set a default value for a destructed array that doesn't have the specified index?

Similar to destructing an object in ES6, where if the passed object doesn't have the property (in the following example, the name prop), it will have a default value:

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

I'm currently destroying an array like the following:

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

However, I want the 'id' to be optional, so that $this->id can pick up 0 as a default value when no 'id' is passed.

1

There are 1 best solutions below

2
On

This works for me:

<?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