3 ms·
The use clause is the weird part. I would imagine the reason it has to be there is because it would be bad if functions that weren't written with closures in mi
by zaphar 13y ago
The use clause is the weird part. I would imagine the reason it has to be there is because it would be bad if functions that weren't written with closures in mind previously suddenly turned into closures. Otherwise why even bother?
- smsm42 13y agoThe reason has nothing to do with that. The reason is that closures don't need most of the variables from parent scope, but if they were imported, since PHP is refcounting they'd keep a lock on those variables even after exit from the original scope - as long as the closure exists - even though nobody actually needs them. Since PHP has $$var (and other things like this) we can not know in advance which variables the function uses in local scope, so if we did automatic scope importing, we'd have to keep the whole scope of the parent function for the lifetime of the closure in case some of the variables would be needed. This, if parent scope contained some large objects, would result in a memory and performance hit each time closures are used. Thus, it was decided that we'd make scope importing explicit (the use clause), so if you want to import variable, you have to say it. Experience shows that vast majority of closures need no more than one or two vars from parent scope, so the tradeoff is fine. Of course, if closures would import dozens of variables regularly, we'd have to seek different solution, but this is not the situation. Additional benefit - though not the reason - is readability improvement, as now you know where each variable is coming from, otherwise reading in-closure code you wouldn't know if the variable that is not mentioned anywhere is a mistake or it is actually expected to be imported from outside. BTW, C++11 is using the same idea: https://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B https://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B though they have catch-all syntaxes which in PHP wouldn't work since PHP is a dynamic language.
- zaphar 13y agoThat was a very informative explanation thank you. I still think it looks weird even if PHP's semantics make it necesary but that's totally subjective :-)