coding-standard icon indicating copy to clipboard operation
coding-standard copied to clipboard

New sniff suggestion: only static anonymous functions

Open zerkms opened this issue 4 years ago • 0 comments

Non-static anonymous functions when used inside classes create a closure for $this even if it's not used. So far so good - there is a sniff for that already.

But, the problem is that non-static anonymous functions with legit $this uses may create extremely hard to debug memory leaks caused by circular references.

Hence I suggest to create a sniff that forbids non-static anonymous functions entirely. If one needs a reference to the current instance they may pass it explicitly, eg $that = WeakReference::create($this); and pass use($that).

Demo of the hard to notice leak: https://3v4l.org/6n41t (see that the object must first be destructed, then the script finish, not the other way around) And alternative implementation with weak references: https://3v4l.org/o1KC8

Given WeakReference became only available in 7.4 - the rule may be conditional to php >= 7.4

This rule seems to be very easy to implement, I would contribute it if core dev team agrees it will be accepted.

zerkms avatar Oct 08 '21 07:10 zerkms