Ambrosius Topor

Notiz — 2020-04-21

Destructuring Assignment in JavaScript and PHP

Example in JavaScript

Object destructuring

function getPage() {
    return {
        title: 'An Example Title',
        lead: 'Lorem ipsum'
    }
}
const { title, lead } = getPage()
// title = An Example Title
// lead = Lorem ipsum

It is also possible to assign the keys to different variable names:

const { title: heading, lead: introduction } = getPage()
// heading = An Example Title
// introduction = Lorem ipsum

Example in PHP

Function providing the data

private function parsePath(Path $path) : array
{
    $parts = explode('/', $path->getRoute(), 3);
    array_shift($parts);
    return [
        'year' => $parts[0],
        'path' => $parts[1],
        'date' => substr($parts[1], 0, 10),
        'name' => substr($parts[1], 11),
    ];
}

Extracting the data using 'extract'

There is a function available in PHP (already since version 4), which can be used to pull out variables from an array:

public function build(array $options)
{
    extract($this->parsePath($options['path']));
    // $year, $path, $date, $name are available at this point
}

In the context of a function it is quite safe, but one still needs to be careful not to import untrusted (potentially harmful) data, or overwrite local variables.
Also, it is not obvious (rather magic) what is exactly happening.

For some improvement, we could use the EXTR_IF_EXISTS option and set the variables beforehand:

public function build(array $options)
{
    $year = '';
    $path = '';
    $date = '';
    $name = '';
    extract($this->parsePath($options['path']), EXTR_IF_EXISTS);
}

Another variation (but losing information, e.g. for IDE support):

public function build(array $options)
{
    extract(array_flip(['year', 'path', 'date', 'name']));
    extract($this->parsePath($options['path']), EXTR_IF_EXISTS);
}

Makes me think that there should be another option to define which variables to extract:

public function build(array $options)
{
    extract($this->parsePath($options['path']), /* hypothetical */ EXTR_LISTED, ['year', 'path', 'date', 'name']);
}

Extracting the data using 'list'

Since PHP 7.1, the list function allows to 'map' arrays:

public function build(array $options)
{
    list('path' => $path, 'year' => $year, 'name' => $name, 'date' => $date) = $this->parsePath($options['path']);
    // $year, $path, $date, $name are available at this point
}

Also, there is a shorthand syntax:

public function build(array $options)
{
    ['path' => $path, 'year' => $year, 'name' => $name, 'date' => $date] = $this->parsePath($options['path']);
}

Granted, it is more verbose—but it is clear which variables get assigned without having to peek into the method.

References

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment