Alex
Alex

Reputation: 1

PHP function($param1)($_REQUEST, $e){...} what's the second parentheses, where to read?

Met a function call of the form:

$response = controller($activePage)($_REQUEST);

and the function itself of the form:

function controller(string $name) {......}

question: Where can you read - what the second brackets mean.

In the PHP documentation, function arguments are enclosed in single parentheses

Upvotes: 0

Views: 43

Answers (2)

KodeFor.Me
KodeFor.Me

Reputation: 13521

It seems like the controller function returns back a closure (aka: anonymous functions) function, which means that the second parentheses are the call of the closure.

The simplification of this code: $response = controller($activePage)($_REQUEST); is this:

$callback = controller($activePage);
$response = $callback($_REQUEST);

The controller could look like that inside:

function controller($page) {
    return function($request) {
       // Do some work here
       // ...
       // and return something

       return $result;
    }
}

Finally, based on the documentation related to anonymous functions, if you need to use some variables coming from the parent function body, you could use the use like that:

function controller($page) {
    $page = str_replace('something', 'i-do-a-test', $page);
    
    return function($request) use ($page) {
       $result = 'my-slug-' . $page;
       // Do some work here
       // ...
       // and return something

       return $result;
    }
}

Upvotes: 0

jibsteroos
jibsteroos

Reputation: 1391

What you have there is a function call to:

controller($activePage)

This call returns a function, that takes as an argument $_REQUEST and is executed in turn.

E.g.

function controller(string $name): callable
{
    return function ($param) {
        var_dump($param); // show contents of $_REQUEST
    };
}

Note: for more on callbacks

Working demo

Upvotes: 1

Related Questions