3

What does this statement mean in php,

PHP supports first-class functions

Would anyone explain briefly, I seems not to understand while reading the documentation.

I would appreciate an example.

Dharman
  • 30,962
  • 25
  • 85
  • 135
muya.dev
  • 966
  • 1
  • 13
  • 34

2 Answers2

5

Wikipedia:

This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

Originally you could assign function as strings or arrays to variables:

$aFunction = 'someFunctionName';
$aFunction();
$aMethod = [$object, 'someMethodName'];
$aMethod();

You might see that in old source. It is an indirect reference to the function/method (by its name). Current PHP provides better ways. You can assign an anonymous function directly to a variable:

$aFunction = function(...$arguments) {
  var_dump($arguments);
};
$aFunction();

Or implement the magic method '__invoke()' in a class:

class A {
  public function __invoke(...$arguments) {
    var_dump($arguments);
  }
}

$aFunction = new A();
$aFunction(1, 2);

In PHP 7.4 shortcut function for simple expressions were added:

$aFunction = fn(...$arguments) => var_dump($arguments);
$aFunction(1, 2);
ThW
  • 19,120
  • 3
  • 22
  • 44
2

It means that PHP functions can be treated as variables. They can be saved, passed as arguments to functions and so on.

For example:

$square = fn(int $a) => $a**2;

echo (fn($func) => $func(3))($square);
Dharman
  • 30,962
  • 25
  • 85
  • 135