Search code examples
phpclosures

PHP closure as an optional function argument


Would be possible to specify a default argument value when argument is a PHP closure? Like:

public function getCollection($filter = function($e) { return $e; })
{
    // Stuff
}

Am i missing something (maybe a different syntax?) or it's not possible at all? Of course i know i can do:

public function getCollection($filter = null)
{
    $filter = is_callable($filter) ? $filter : function($e) { return $e; };
    // Stuff
}

(NOTE: I didn't test the above code)


Solution

  • Default arguments can only be "scalar arguments", arrays, or NULL.

    "scalar values" in PHP are numbers, strings, and booleans.

    If you want a function to be a default argument, you're gonna need to use the 2nd way, the 1st is a syntax error.