Joe's
Digital Garden

PHP 8

Notes on new things in PHP that I'm excited to try out.

We now have named arguments in PHP. This introduces some exciting new patterns when combined with changes in variadics but at the expense that argument names are now part of the function signature.

Named Arguments

// Don't need to specify "now" which has a default value
$now = new DateTime(timezone: new DateTimezone('UTC'));

Variadic Function Love

function foo(int ... $values): int {
    return array_sum($values);
}
foo(1, 2); // 3
foo(1, 2, 3); // 6
foo([1, 2]); // 3
$args1 = [1, 2];
$args2 = [3, 4];
foo(...$args1, ...$args2); // 10

Combining Named Arguments with Variadic Functions

$args = ['now', new DateTimezone('UTC')];
$now = new DateTime(...$args);

// or since 'now' has a default value we can define us an assoc array...
$args = ['timezone' => new DateTimezone('UTC')];
$now = new DateTime(...$args);

Also Useful in Constructors

class Person
{
    private $first;
    private $last;
    private $phone;
    private $email;

    public function __construct(string $first, string $last, ...$options)
    {
        $this->first = $first;
        $this->last = $last;
        $this->phone = $options['phone'] ?? '';
        $this->email = $options['email'] ?? '';
    }
}

new Person('James', 'Kirk', ...['email' => 'kirk@example.com');
new Person('James', 'Kirk', email: 'kirk@example.com');
new Person(...['first' => 'James', 'last' => 'Kirk', 'email' => 'kirk@example.com']);

External References

  1. Baker, Mark. Named Arguments and Variadics in PHP 8. Mark Baker's Blog. Retrieved 2021-10-09.

Linked References