gpt4 book ai didi

PHP 匿名函数作为默认参数?

转载 作者:行者123 更新时间:2023-12-03 04:14:56 25 4
gpt4 key购买 nike

有没有办法在 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 默认函数参数只能是标量或数组类型:

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 匿名函数作为默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com