1.2.153. Closure May Use $this

$this is automatically accessible to closures.

When closures were introduced in PHP, they couldn’t use the $this variable, making is cumbersome to access local properties when the closure <https://www.php.net/`closure>`_ was created within an object. This is not the case anymore since PHP 5.4.

<?php

// Invalid code in PHP 5.4 and less
class Test
{
    public function testing()
    {
        return function() {
            var_dump($this);
        };
    }
}

$object = new Test;
$function = $object->testing();
$function();

?>

See also Anonymous functions.

1.2.153.1. Specs

Short name

Php/ClosureThisSupport

Rulesets

All, Changed Behavior, CompatibilityPHP53

Exakat since

0.8.4

PHP Version

With PHP 5.4 and older

Severity

Minor

Time To Fix

Quick (30 mins)

Changed Behavior

PHP 5.4 - More

Precision

Very high

Features

closure, $this

Available in

Entreprise Edition, Exakat Cloud