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)
A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure. use is early binding. That means the variable values are COPIED upon DEFINING the closure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With