1.2.111. 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.111.2. Connex PHP features¶
1.2.111.2.1. Suggestions¶
Remove the static keyword
Remove the call to bindTo() method
Remove the usage of the $this variable
1.2.111.2.2. Specs¶
Short name |
Functions/CannotUseStaticForClosure |
Rulesets |
|
Exakat since |
2.2.2 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Medium |
Available in |