Skip to content

StaticClosureCanBeUsed ​

info on by default quick-fix PHP ≥ 5.4

Group: Code style · PhpStorm name: StaticClosureCanBeUsedInspection

A closure (or arrow function) that never touches the object it was created in can be declared static. That prevents an implicit $this binding, makes the scope explicit and avoids keeping the surrounding object alive.

Example ​

php
<?php
abstract class Base {
    public function work() {}
    public static function tool() {}
}

final class Runner extends Base {
    private $limit = 3;

    public function cases() {
        $squares = array_map(function ($n) { return $n * $n; }, [1, 2]);
        $capped  = array_map(function ($n) { return min($n, $this->limit); }, [4]);
        $helper  = array_map(function ($n) { return parent::tool(); }, [5]);
        $inst    = array_map(function ($n) { return parent::work(); }, [6]);
        $noop    = array_map(function () { ; }, []);
        $empty   = array_map(function () {}, []);
        $twice   = array_map(fn ($n) => $n * 2, [7]);
        $self    = array_map(fn ($n) => $n + $this->limit, [8]);
    }

    public function rebinding() {
        $detached = function () { return 42; };
        $copy = Closure::bind($detached, null, self::class);
        $other = $detached->bindTo(null);

        $attached = function () { return 7; };
        $attached->bindTo($this);
    }

    public function dispatching($queue) {
        $job = function () { return 'ok'; };
        Registry::push($job);

        $task = function () { return 'later'; };
        $queue->push($task);

        new Worker(function () { return 1; });
    }

    public function scopedMap() {
        return ['a' => function () { return 1; }];
    }
}

$routes = [
    'home' => function () { return 'index'; },
    'about' => static function () { return 'about'; },
];
$plain = [function () { return 0; }];

Reported:

  • line 11: Closure does not use $this; declare it static.
  • line 13: Closure does not use $this; declare it static.
  • line 15: Closure does not use $this; declare it static.
  • line 17: Closure does not use $this; declare it static.
  • line 22: Closure does not use $this; declare it static.
  • line 31: Closure does not use $this; declare it static.
  • line 46: Closure does not use $this; declare it static.

Options ​

OptionTypeDefaultEffect
SUGGEST_FOR_SHORT_FUNCTIONSbooltrueWhen false, arrow functions are never reported.

Configure ​

In custos.json:

json
{
  "rules": {
    "StaticClosureCanBeUsed": {
      "enabled": false,
      "options": {
        "SUGGEST_FOR_SHORT_FUNCTIONS": true
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore StaticClosureCanBeUsed

/**
 * @noinspection StaticClosureCanBeUsedInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.