Php static anonymous function

In PHP, anonymous functions are also known as “closures”. They are functions that do not have a specific name and can be assigned to variables or passed as arguments to other functions. A static anonymous function, on the other hand, is a closure that is defined with the “static” keyword. This means that the function will preserve its state between multiple invocations.

The syntax for defining a static anonymous function in PHP is as follows:

$variableName = static function() { /* function body */ };

Here’s an example that demonstrates how static anonymous functions work:

    
$greeting = static function($name) {
    static $count = 0; // static variable to keep track of invocation count
    $count++;

    return "Hello, {$name}! This function has been called {$count} times.";
};

echo $greeting("John");
echo $greeting("Jane");
    
  

In this example, the static anonymous function is assigned to the variable $greeting. When invoked with a name as an argument, it will return a personalized greeting along with the number of times it has been called. The static variable $count keeps track of the invocation count and retains its value between function calls.

Output:

    
Hello, John! This function has been called 1 times.
Hello, Jane! This function has been called 2 times.
    
  

As you can see, the static anonymous function maintains its internal state (count) even though it is called multiple times. This can be useful for scenarios where you need to maintain some sort of persistence or state across multiple invocations.

Leave a comment