PHP匿名函数作为默认参数? [英] PHP Anonymous Function as Default Argument?
本文介绍了PHP匿名函数作为默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 php 中做到这一点?
Is there a way to do this in php?
//in a class
public static function myFunc($x = function($arg) { return 42+$arg; }) {
return $x(8); //return 50 if default func is passed in
}
推荐答案
PHP 默认函数参数只能是标量或数组类型:
PHP Default function arguments can only be of scalar or array types:
默认值必须是常量表达式,而不是(例如)变量、类成员或函数调用.
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
From: PHP Manual / Function Arguments / Default argument values
怎么样:
public static function myFunc($x = null) {
if (null === $x) {
$x = function($arg) { return 42 + $arg; };
}
return $x(8); //return 50 if default func is passed in
}
这篇关于PHP匿名函数作为默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文