6 ms·
That has to be one of the strangest syntax's I've seen for closures ever. I get why it has to be that way sort of. (backwards compatibility) but it only serves
by zaphar 13y ago
That has to be one of the strangest syntax's I've seen for closures ever. I get why it has to be that way sort of. (backwards compatibility) but it only serves to illustrate how PHP has hamstrung itself in the past.
Comparing PHP's evolution to C++ isn't exactly flattering either.
- smsm42 13y agoWhat's so strange in it? It looks pretty much exactly like JS, for example, with one small addition of "use" clause. It has very little to do with "backwards compatibility" - since there's nothing to be backwards compatible to, closures didn't exist before.
- zaphar 13y agoThe 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 :-)