1.2.270. Could Be Static Closure¶
Closure <https://www.php.net/manual/en/class.`closure.php>`_ and arrow functions may be static, and prevent the import of $this
.
By preventing the useless import of $this
, you avoid useless work.
This also has the added value to prevent the usage of $this
from the closure <https://www.php.net/`closure>`_. This is a good security practice.
This is a micro-optimisation. Apply it in case of intensive usage.
<?php
class Foo
{
function __construct()
{
// Not possible to use $this
$func = static function() {
var_dump($this);
};
$func();
// Normal import of $this
$closure = function() {
var_dump($this);
};
}
};
new Foo();
?>
See also Anonymous functions, GeneratedHydrator and Static anonymous functions.
1.2.270.1. Connex PHP features¶
1.2.270.1.1. Suggestions¶
Add the static keyword to the closure.
Make actual usage of $this in the closure.
1.2.270.1.2. Specs¶
Short name |
Functions/CouldBeStaticClosure |
Rulesets |
|
Exakat since |
1.3.2 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |