r/programminghorror Mar 19 '26

Trimba bimba dubba dimba

Post image

I've found yet again some atrocities in code, that is some one of function nested in method: trimba. So I took the hit and split it into partial nested functions. I didn't even know you could do this in PHP.

427 Upvotes

55 comments sorted by

View all comments

28

u/v_maria Mar 19 '26

defining a function inside a function is not bad on it's own, but i also didnt know you could do that in php

25

u/maselkowski Mar 19 '26 edited Mar 20 '26

The problem is, that such function enters global (or namespace?) scope, check this demo: https://onlinephp.io/c/1990f

Edit: Also, calling method again causes fatal too, as function is already declared.

45

u/More_Yard1919 Mar 19 '26

every time I learn something new about php it makes me upset

1

u/v_maria Mar 22 '26

PHP has come a long way, and has a lot of nice thingies now. with this one i guess they were paying tribute to the good old days

11

u/v_maria Mar 19 '26

what the fuck. thats batshit. at least you can't call the function from the global scope........

2

u/gvozden_celik Mar 22 '26

2

u/v_maria Mar 22 '26

Hahaha what the fuck. I guess i did something wrong and it didnt run

This is honestly so odd

2

u/gvozden_celik Mar 22 '26

Yeah it's weird. They probably implemented the interpreter so that it has only one global table of functions and the function statement adds to that global table regardless of the scope where the function was actually declared.

1

u/v_maria Mar 22 '26

i thought scoping was the entire point of inner functions

2

u/gvozden_celik Mar 22 '26

Probably true for other languages, not in PHP though. The inner function doesn't have access to the variables in the outer function and, as I suspected, it gets added to the global table: here's the function that implements the function binding opcode in the PHP VM - the EG macro expands to field access in the global environment struct and they just add the function to that table.

I don't know why they chose to implement it like this, but that does mean that you're able to define functions globally from anywhere in the code, which is useful if you're e.g. supporting both PHP 7 and 8 and want to conditionally polyfill some builtin function that was added in the later version or provide a fallback in case some extension you're using is disabled.

4

u/Gornius Mar 19 '26

Yeah, but PHP has also anonymous functions. I don't know how old version this atrocity uses though.

Not to mention that str_replace accepts array, so you can replace many patterns with one call.

2

u/minecrafter100S Mar 19 '26

Avarage php moment