PHP closure as an optional function argument
Asked Answered
P

2

16

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)

Photon answered 14/5, 2012 at 15:48 Comment(0)
D
18

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.

Discomfort answered 14/5, 2012 at 15:55 Comment(3)
Oh, i see. So my question is useless. Thanks anyway.Photon
@Gremo: It's not a useless question, it's a good question. Others may be wondering the same thing :-)Discomfort
Agreed. I'm a PHP dev but still found this interesting.Efrenefron
P
0

What about the following?

public function getCollection(?Closure $filter = null)
{
     $filter ??= fn($e) => $e;
     // Stuff
}
Poaceous answered 27/5, 2024 at 11:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.