Function literals in both C++ and PHP require programmer to specify which variables they are using from the current lexical context. What’s the reason behind this requirement?
I guess it’s not meant for the compiler/interpreter, because one can statically infer this information from function literal’s body. Is it only for drawing the reader’s attention?
For C++11 at least,
[=] () {...}will automatically pull in all and only those local variables which the function body uses. (Or, equally,[&]...)You can specify individual variables to be captured by reference or by value if you have any specific needs beyond this catch-all.
In PHP, variables are created when their name is first used, so I expect the declaration is to make sure no new variables mask the old ones. A bit like the
globalkeyword.