Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP closure as an optional function argument

Tags:

closures

php

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)

like image 400
gremo Avatar asked May 14 '12 15:05

gremo


People also ask

What is closure function PHP?

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.

Is closure and anonymous function same?

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.

What is a closure in PHP and why does it use the use identifier?

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.


1 Answers

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.

like image 177
Rocket Hazmat Avatar answered Sep 28 '22 18:09

Rocket Hazmat