16

当参数是 PHP 闭包时,是否可以指定默认参数值?喜欢:

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

我错过了什么(可能是不同的语法?)还是根本不可能?我当然知道我能做到:

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

注意:我没有测试上面的代码)

4

1 回答 1

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.

于 2012-05-14T15:55:00.440 回答