PHP闭包作为可选的函数参数 [英] PHP closure as an optional function argument
本文介绍了PHP闭包作为可选的函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当参数是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)
推荐答案
默认参数只能是标量参数,数组或NULL。
Default arguments can only be "scalar arguments", arrays, or NULL.
PHP中的标量值是数字,字符串和布尔值。
"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.
这篇关于PHP闭包作为可选的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文