1.2.269. 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.269.1. Suggestions

  • Add the static keyword to the closure.

  • Make actual usage of $this in the closure.

1.2.269.2. Specs

Short name

Functions/CouldBeStaticClosure

Rulesets

All, Changed Behavior, Suggestions

Exakat since

1.3.2

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class

Examples

Piwigo

Available in

Entreprise Edition, Exakat Cloud