Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Anonymous Function as Default Argument?

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
}
like image 454
Arcymag Avatar asked Oct 27 '25 10:10

Arcymag


1 Answers

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
}
like image 142
Luke Avatar answered Oct 29 '25 01:10

Luke