1.2.1235. Unbinding Closures

Never drop $this, once a closure <https://www.php.net/`closure>`_ was created in a non-static method.

From the PHP wiki : “Currently it is possible to unbind the $this variable from a closure <https://www.php.net/`closure>`_ that originally had one by using $`closure <https://www.php.net/`closure <https://www.php.net/closure>`_>`_->bindTo(null). Due to the removal of static calls to non-static methods in PHP 8, we now have a guarantee that $this always exists inside non-static methods. We would like to have a similar guarantee that $this always exists for non-static closures declared inside non-static methods. Otherwise, we will end up imposing an unnecessary performance penalty either on $this accesses in general, or $this accesses inside such closures.”

Calling bindTo() with a valid object is still valid.

<?php

class x {
    private $a = 3;

    function foo() {
        return function () { echo $this->a; };
    }
}

$closure = (new x)->foo();

// $this was expected, and it is not anymore
$closure->bindTo(null);

$closure->bindTo(new x);

?>

See also Unbinding $this from non-static closures.

1.2.1235.1. Suggestions

  • Create a static closure, which doesn’t rely on $this at all

  • Remove the call to bindTo(null).

1.2.1235.2. Specs

Short name

Functions/UnbindingClosures

Rulesets

All, CE, CompatibilityPHP74

Exakat since

1.9.0

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

closure, closure-binding

Available in

Entreprise Edition, Community Edition, Exakat Cloud