PHP closure as an optional function argument

徘徊边缘 提交于 2019-12-08 14:56:03

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/10586695/php-closure-as-an-optional-function-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!