4

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
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Arcymag
  • 1,037
  • 1
  • 8
  • 18
  • can I ask why you want to do it this way? – tradyblix Oct 11 '12 at 03:24
  • well, I have a general utility function that takes anonymous function as an argument (specifically, it converts an assortment of objects into an assortment of arrays according to certain rules, which are performed by functions). I'd like to have a default action. Is that too much to ask? =x – Arcymag Oct 11 '12 at 03:26
  • No. Default parameters can only be constant values, not expressions, nor objects. – mario Oct 11 '12 at 03:34

2 Answers2

9

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
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Luke
  • 344
  • 2
  • 9
  • answer accepted because of link to php manual which says "The default value must be a constant expression, not (for example) a variable, a class member or a function call." Thanks. I had something like this earlier, and I hoped there was a language feature for it. Guess not =( – Arcymag Oct 11 '12 at 03:37
  • I would also advise declaring the type for `$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. – Anthony Mar 01 '18 at 20:53
3

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 
} 
Robbie
  • 17,605
  • 4
  • 35
  • 72