2

Is it possible for a PHP function which has a lambda parameter to have a default value?

While the following works fine:

function calcValue($func) {
  echo $func(5);
}

calcValue(function($a){return 2*$a;});

when I try:

function calcValue($func = function($a){return 2*$a;}) {
  echo $func(5);
}

I get a parse error:

Parse error: syntax error, unexpected 'function' (T_FUNCTION)
Silveri
  • 4,836
  • 3
  • 35
  • 44

2 Answers2

1

A default value must be a constant expression. See this question for more details: PHP Anonymous Function as Default Argument?

Community
  • 1
  • 1
1

Default values in function calls have to be constants. They cannot be a dynamic value/expression result.

good: function($foo = 'bar');
bad:  function($foo = bar());
bad:  function($foo = 'ba' . 'r'); // to PHP it's still an expression.

Ref: http://php.net/manual/en/functions.arguments.php

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    PHP 5.6 will support constant scalar expression (3rd variant) - see https://wiki.php.net/rfc/const_scalar_exprs – ThW Dec 02 '13 at 19:21