What Are Static Anonymous Functions in PHP?

Find out what the static keyword means in PHP when used with anonymous functions / closures

Starting PHP 5.4+, one of the uses of the static keyword in PHP is to define static anonymous functions / closures. Read below to understand what they are and how they differ from non-static anonymous functions / closures.

Non-static Anonymous Functions

Before we dive into static anonymous functions, let's quickly go over the behavior of non-static anonymous functions.

When a closure is declared within the context of a class, the default behavior is that the class is automatically bound to the closure. What that means is that $this is available inside of the anonymous function's scope. Let's consider the following example:

class Foo
{
    public function bar()
    {
        return function() {
            var_dump($this);
        };
    }
}

$foo = new Foo();
$func = $foo->bar();
$func();

The code above would output: object(Foo)#1 (0) { }. From the result we can see how $this refers to the class the closure was defined in.

Static Anonymous Functions

Simply put, static anonymous functions prevent:

  1. The automatic binding of a class to the closure defined within the its context;
  2. Binding of objects to the closure at runtime.

To illustrate this, let's consider the following examples:

class Foo
{
    public function bar()
    {
        return static function() {
            var_dump($this);
        };
    }
}

$foo = new Foo();
$func = $foo->bar();
$func();

This would result in: Notice: Undefined variable: this in %s on line %d NULL.

Now let's see what happens when we try to bind an object to the anonymous function at runtime:

$func = static function() {
    // ...
};

$func = $func->bindTo(new StdClass());
$func();

This would result in: Warning: Cannot bind an instance to a static closure in %s on line %d.

When to Use Static Closures?

In general, static closures provide micro-optimization (for e.g., by improving hydration performance when dealing with private properties). You should consider using static closures when:

  1. You are certain you won't need to reference the class within the function scope;
  2. You don't have the need to bind an object to the function scope at runtime;
  3. You are looking for areas to optimize your code.

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.