In Python you can have the following:
def foo(param1, param2):
def bar():
print param1 + param2
bar()
I am having some difficulties with this behaviour in PHP though.
I expect this to work in the following way:
function foo($param1, $param2)
{
function bar()
{
echo $param1 + $param2;
}
bar();
}
But that fails. So I read some about closures (this is called a closure is it not? It is in Python, that I know). And in the php documentation about anonymous functions (which they said to have been implemented as closures) they tell you to use the use() expression in the following manner:
function foo($param1, $param2)
{
function bar() use($param1, $param2)
{
echo $param1 + $param2;
}
bar();
}
But that still fails. So I changed it to the PHP-anonymous function a-like like this:
function foo($param1, $param2)
{
$bar = function() use($param1, $param2)
{
echo $param1 + $param2;
};
$bar();
}
That does work, however it just looks really ugly. Am I missing something? Can I improve this in any way? Or will I just have to use the ‘ugly’ way?
(I am not looking for a discussion about if closures are useful)
I couldn’t find the
function bar() use($param1, $param2)syntax on the manual page you linked to, just the “ugly” version that works (which is truly anonymous). I guess you’ll have to use that.On your second example,
baris not a closure. To create a closure in PHP you have to use the uglyuse, or theClosureclass. Every function will create its own local scope, but closures are not automatic.PHP seems to have an odd definition for the term “closure”, as you probably noted when you read the manual. They define it as a synonym for “anonymous function”:
Confusing, right? Later, they explain you need the
usekeyword if you want to inherit the parent scope:The PHP Wiki rfc page on closures gives us some hints on why closures were implemented this way: