2

I am not able to understand the code, that is something like :- $this->array[$key]($parameter)

Why is there ($parameter) after $this->array[$key] ?

Thanks

John Cargo
  • 1,839
  • 2
  • 29
  • 59

2 Answers2

6

For reference, the code snippet being referred to here is the following one-line function:

/**
 * Call a custom driver creator.
 *
 * @param  string  $name
 * @param  array  $config
 * @return mixed
 */
protected function callCustomCreator($name, array $config)
{
    return $this->customCreators[$config['driver']]($this->app, $name, $config);
}

The value being held at the location denoted by $this->customCreators[$config['driver']] in that code snippet is a function. You normally call a named function like this:

functionName();

The open/close parentheses tells PHP to call/execute that function rather than just reference it, meaning you can pass that function around to a separate function as a parameter like this:

anotherFunction($this->customCreators[$config['driver']]);

function anotherFunction($creatorFn) {
    $creatorFn();
}

PHP added support for lambda-style functions (PHP uses the term 'anonymous') in version 5.3, which is when you can say we started treating functions as first-class citizens.

Community
  • 1
  • 1
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
5

In the code you referenced, the array contains a function which gets called with the specified parameters. It's just a regular function call, but the function (or rather a reference to it) is stored in the array.

Franz
  • 399
  • 2
  • 6
  • Technically, the example OP provided wouldn't actually work, as `[]` is used solely for pushing elements onto the array. – rdiz Jan 19 '16 at 15:21
  • 1
    Yeah, the code line he posted in the question wouldn't work. I was referring to the GitHub link he posted. – Franz Jan 19 '16 at 15:26