In Python, you can get the following:
def foo(param1, param2): def bar(): print param1 + param2 bar()
I am having some difficulties with this behavior in PHP. I expect this to work as follows:
function foo($param1, $param2) { function bar() { echo $param1 + $param2; } bar(); }
But it fails. So I read some about closing (this is called closing, isn't it? It's in Python that I know). And in the php documentation about anonymous functions (which they said were implemented as closure), they tell you to use use () expression like this:
function foo($param1, $param2) { function bar() use($param1, $param2) { echo $param1 + $param2; } bar(); }
But this still fails. So I changed it to a PHP-anonymous function a-like as follows:
function foo($param1, $param2) { $bar = function() use($param1, $param2) { echo $param1 + $param2; }; $bar(); }
It really works, but it looks very ugly. Am I missing something? Can i improve this? Or do I just need to use the ugly way?
(I'm not looking for a discussion on whether closures are useful)
Daan timmer
source share