r/PHPhelp • u/BaronOfTheVoid • Dec 09 '25
Static Function outside of classes
I know, it doesn't make any sense.
To make it clear this is about closures/callables that you can for example pass on to another function, like this: https://3v4l.org/5qegC
I have seen it in the codebase I'm working on and don't have any clue what it actually differentiates from just leaving the static keyword out, if anything. Couldn't find anything related on SO or the PHP docs either.
And I was actually expecting PHP to tell me "unexpected keyword static" or something along the lines, or if not PHP itself then at least one of the code quality tools like phpstan, cs, md and so on, or PhpStorm. But it isn't considered wrong by any of these tools.
Maybe because they didn't expect a dev could be that silly to use the static keyword outside classes.
Now I'm expecting that it at least doesn't do anything, that there is no harm in it. But maybe someone with a deeper understanding of how PHP works internally could clear that up. Thanks in advance.
View all comments
Show parent comment
2
u/obstreperous_troll Dec 10 '25 edited Dec 10 '25
Because the non-static version captures
$thisuniquely on each instance. I changed it to this version https://3v4l.org/gTIVv/vld#vnull and still don't see a difference in VLD. Obviously b() won't even work if you call it, but the point is VLD doesn't show a difference, and it probably just doesn't expose whatever internal flag affects its capture behavior at runtime.Still, adding
staticto closures seems to me to be a "micro" enough optimization that it's not worth the noise, and I'm just going to turn off the IDE inspection. Might be good for avoiding memory leaks if you're prone to storing those closures in a longer-lived scope, since they'll continue to hold a reference to$this, but if you're doing that sort of thing, you probably need the reference in the first place.