Marcin Lentner
Marcin Lentner

Reputation: 85

anonymous function as an argument to custom function in php

Is there a way in PHP to call an anonymous function in the definition of a custom function and pass it as an argument?

I've got this function

function foo( $message = function() {  
        return 'bar';
    }) {
    return $message;
}
echo foo();

This produces an error:

Fatal error: Constant expression contains invalid operations

Is the syntax wrong or is there no way of doing it?

Upvotes: 0

Views: 51

Answers (1)

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28874

From PHP Documentation:

The default value must be a constant expression, not (for example) a variable, a class member or a function call. PHP also allows the use of arrays and the special type NULL as default values

So, basically you cannot set a throwable (function) as Default value.

Instead, you can try something like below:

function foo( $message = null ) {

    // If using default value
    if (!isset($message)) {

        // You can now define your default anonymous function behaviour
        $return = function() { return 'bar';}; 
    }

    // Now, you can return the anonymous function handle
    return $return();
}
echo foo();

Rextester DEMO

Upvotes: 1

Related Questions