php 中作为自定义函数参数的匿名函数
anonymous function as an argument to custom function in php
PHP有没有办法在自定义函数的定义中调用匿名函数并将其作为参数传递?
我有这个功能
function foo( $message = function() {
return 'bar';
}) {
return $message;
}
echo foo();
这会产生一个错误:
Fatal error: Constant expression contains invalid operations
语法错误还是没有办法?
The default value must be a constant expression, not (for example) a
variable, a class member or a function call. PHP also allows the use
of arrays and the special type NULL as default values
所以,基本上你不能将可抛出的(函数)设置为默认值。
相反,您可以尝试如下操作:
function foo( $message = null ) {
// If using default value
if (!isset($message)) {
// You can now define your default anonymous function behaviour
$return = function() { return 'bar';};
}
// Now, you can return the anonymous function handle
return $return();
}
echo foo();
PHP有没有办法在自定义函数的定义中调用匿名函数并将其作为参数传递?
我有这个功能
function foo( $message = function() {
return 'bar';
}) {
return $message;
}
echo foo();
这会产生一个错误:
Fatal error: Constant expression contains invalid operations
语法错误还是没有办法?
The default value must be a constant expression, not (for example) a variable, a class member or a function call. PHP also allows the use of arrays and the special type NULL as default values
所以,基本上你不能将可抛出的(函数)设置为默认值。
相反,您可以尝试如下操作:
function foo( $message = null ) {
// If using default value
if (!isset($message)) {
// You can now define your default anonymous function behaviour
$return = function() { return 'bar';};
}
// Now, you can return the anonymous function handle
return $return();
}
echo foo();