Sobes.tech
Junior — Middle

Is it necessary to use the keyword this in a class method when creating a closure inside it?

sobes.tech AI

Answer from AI

In PHP, when creating a closure (Closure) inside a class method, the keyword this does not need to be explicitly used if the closure is declared within the method and does not use use. Inside such a closure, this is available automatically starting from PHP 5.4.

However, if the closure is created outside the object context or passed as a callback, to access the object's properties and methods, you need to either use use ($this) or declare the closure as a class method.

Example:

class MyClass {
    private $value = 10;

    public function getClosure() {
        return function() {
            return $this->value; // $this is available without use
        };
    }
}

$obj = new MyClass();
$closure = $obj->getClosure();
echo $closure(); // Outputs 10

If the closure is created outside the method, $this must be explicitly passed:

$closure = function() use ($this) {
    return $this->value;
};
Is it necessary to use the keyword this in a class… - sobes.tech