DEV Community

spO0q 🐒
spO0q 🐒

Posted on

PHP variadic

Variadic functions accept a "non-fixed" (a.k.a. variable) number of arguments.

The term is used for variable-length argument lists.

Old fashion vs. ...

The old way of writing variadic functions would be:

function myFunc()
{
    $args = func_get_args();
    print_r($args);
}
Enter fullscreen mode Exit fullscreen mode

But you can use the ... token instead (since 5.6):

function myFunc(...$args)
{
    print_r($args);
}
Enter fullscreen mode Exit fullscreen mode

You can even have several "fixed" arguments and a variadic argument:

function myFunc($param1, $param2, ...$args)
{
    print_r($param1);
    print_r($param2);
    print_r($args);
}
Enter fullscreen mode Exit fullscreen mode

In such case, there can be only one variadic argument, though, and it must be placed after other fixed arguments.

N.B.: To prevent any fatal error, always place the variadic argument at the end of the signature.

When to use?

When you need to pass an unlimited number of arguments to a function.

The inbuilt printf or sprintf are good examples of variadic functions.

Typehinting

function myFunc(Post ...$posts)
{
    print_r($posts);
}
Enter fullscreen mode Exit fullscreen mode

You can typehint variadic arguments, but the variadic parameter will be treated as an array, which is convenient to create loops and conduct common operations on arguments.

Variadic arguments in constructors

class Bike {
    private $color;

    public function __construct(private string $model, ...$options) {
        $this->color = $options['color'] ?? 'Blue';
    }
}
Enter fullscreen mode Exit fullscreen mode

N.B.: you can't promote variadic arguments.

Top comments (0)