PHP – Default function argument to new object

  laravel, php

I’m trying to create a function with an optional argument, and if the argument is not passed in then default to an empty Laravel Collection.

I’ve tried the following:

function myFunction(string $string, Collection $collection = [])

Result: Can’t use an array as a default parameter for Collection object

function myFunction(string $string, Collection $collection = collect([]))

Result: constant expression contains invalid operations

function myFunction(string $string, Collection $collection = new Collection)

Result: constant expression contains invalid operations

What I can do is the following:

function myFunction(string $string, Collection $collection = null){
        if ($collection == null){
            $collection = new Collection;
        }
}

Is there a better way to do this or should I stick with what I’ve got?

Source: Ask PHP

LEAVE A COMMENT