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
}
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 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
}
$x in the function signature since passing in a string would result in an error when $x(8) occurs. I personally would go with declaring the type as Closure to ensure it is an anonymous function, but callable would also work and be a bit more flexible (and error prone). So myFunc(Closure $x = null) or myFunc(callable $x = null), either one would throw a catchable fatal error if you tried myFunc("test"); versus a non-catchable fatal error if the type isn't declared.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
}