self Is A Valid Type On A Closure

<?php

class XABC {
    function foo() {
            // static does not apply to self
        $f = static function () : self {
            // __CLASS__ is preserved in the closure
            echo __CLASS__.PHP_EOL;
            return new self();
        };

        return $f;
    }
}

var_dump((new xabc)->foo()());

self is a valid type inside a class (trait, interface, enum) to reference the current class. self may also be used with a closure, since the closure use its location of definition. The class name may be exported that way, and instantiated outside the original class.

This applies to static and parent too. Try it wit static for extra fun.

This tips also applies when the closure is made static, although it might be surprising.

This tip applies to arrow functions.

This tip does not applies to functions created in a class (ugh…).

See Also

PHP Features

Last updated: 14 July 2026