AI Briefing
KO

PHP 8.6 Closure Optimization

·2026.04.14 19:59

Key point

PHP 8.6 will introduce static closure inference and a reuse cache.

Details

Two closure optimizations were proposed as a PHP 8.6 RFC, taking a direction that accepts some BC break in exchange for performance gains.

  • Static closure inference: non-static closures that don't actually use $this are automatically treated as static.

  • This can reduce unnecessary $this capturing and reference cycles between objects and closures.

  • However, the inference isn't complete, and closures are not converted to static when $this could indirectly flow in, such as in the following cases:

    • $$var
    • cases that look like static calls such as Foo::bar() but could be interpreted as instance calls
    • $f()
    • call_user_func()
    • cases where another non-static closure is declared inside
    • require, include, eval
  • When tested on the Symfony Demo after removing explicit static, 68 out of 87 (about 78%) closures could be automatically inferred.

  • Stateless closure caching: closures that are static, capture no variable values, and declare no static variables are stored in a reuse cache.

  • Since identical closures created at the same lexical position are no longer newly created each time, an improvement of about 80% was observed in a very simple benchmark.

  • In the Laravel template, closure instantiation was reduced by 2384 out of 3637, resulting in about 3% performance improvement based on local measurements.

Backward incompatible changes were also summarized.

  • ReflectionFunction::getClosureThis() returns NULL for inferred static closures.
  • Two stateless closures created at the same lexical position may now be treated as the same object.
  • Objects that were previously collected late due to reference cycles may now be garbage collected sooner, which may also cause their destructor to run earlier.
  • Closure::bind() and Closure::bindTo() still fail as before for explicitly static closures, but for closures that became static through inference, passing an object is allowed but ignored.

The vote passed 24:0:1, targeting PHP 8.6.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.