1.2.109. Cannot Use Static For Closure

The reported closures and arrow functions cannot use the static keyword.

Closures that makes use of the $this pseudo-variable cannot use the static keyword, at it prevents the import of the $this context in the closure <https://www.php.net/`closure>`_. It will fail at execution.

Closures that makes use of the bindTo() method, to change the context of execution, also cannot use the static keyword. Even if $this is not used in the closure <https://www.php.net/`closure>`_, the static keyword prevents the call to bindTo().

<?php

class x {
    function foo() {
        // Not possible, $this is now undefined in the body of the closure
        static function () { return $this->a;};
    }

    function foo2() {
        // Not possible, $this is now undefined in the body of the arrow function
        static fn () => $this->a;
    }

    function foo3() {
        // Not possible, the closure gets a new context before being called.
        $a = static fn () => $ba;
        $this->foo4($a);
    }

    function foo4($c) {
        $c->bindTo($this);
        $c();
    }

}
?>

See also Static anonymous functions.

1.2.109.1. Suggestions

  • Remove the static keyword

  • Remove the call to bindTo() method

  • Remove the usage of the $this variable

1.2.109.2. Specs

Short name

Functions/CannotUseStaticForClosure

Rulesets

All, Analyze, Changed Behavior

Exakat since

2.2.2

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Medium

Features

closure, static

Available in

Entreprise Edition, Exakat Cloud