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)

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

PHP 5.6 will support constant scalar expression (3rd variant) - see wiki.php.net/rfc/const_scalar_exprs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.