[wp-trac] [WordPress Trac] #58323: Use static closures whenever $this is not used to avoid memory leaks
WordPress Trac
noreply at wordpress.org
Mon May 15 21:31:34 UTC 2023
#58323: Use static closures whenever $this is not used to avoid memory leaks
-------------------------+-----------------------------
Reporter: westonruter | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version:
Severity: normal | Keywords:
Focuses: performance |
-------------------------+-----------------------------
Historically closures were not usable in WordPress since they were
introduced in PHP 5.3 and WordPress supported PHP 5.2. However, now
WordPress requires PHP 5.6 so closures have started making their way into
the codebase. Whenever a closure is used inside of a class instance, the
`$this` is automatically captured by the closure. If the closure is added
as a filter and not removed, for example, the class instance won't be able
to be garbage collected even if there are otherwise no other references.
For any such closures that don't reference `$this`, this can be avoided by
adding a `static` keyword to the closure. Doing so prevents `$this` from
being captured and thus avoids a memory leak. See
[https://stackoverflow.com/questions/19899468/php-closures-why-the-static-
in-the-anonymous-function-declaration-when-bindin/64481894#64481894 Stack
Overflow answer].
This can be avoided in the future by incoporating the
[https://github.com/slevomat/coding-standard
SlevomatCodingStandard.Functions.StaticClosure] sniff.
Also implemented in [https://github.com/WordPress/performance/pull/729 PR
for Performance Lab plugin].
--
Ticket URL: <https://core.trac.wordpress.org/ticket/58323>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list