PHP Anonymous Function as Default Argument?

偶尔善良 提交于 2019-12-11 01:17:37

问题


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
}

回答1:


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

How about:

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
}



回答2:


You can use func_num_args and func_get_arg

//in a class 
public static function myFunc() { 
    if (func_num_args() >= 1) {
        $x = func_get_arg(0);
    } else {
        $x = function($arg) { return 42+$arg; }
    }
    return $x(8); //return 50 if default func is passed in 
} 

But I agree with tradyblix that you could just process the data as in

//in a class 
public static function myFunc() { 
    if (func_num_args() >= 1) {
        $x = func_get_arg(0);
        $retval = $x(8);
    } else {
        $retval = 42 + 8;
    }
    return $retval; //return 50 if default func is passed in 
} 


来源:https://stackoverflow.com/questions/12831679/php-anonymous-function-as-default-argument

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