According to object-oriented programming expert Martin Fowler, closures are defined as a block of code that can be passed to a function. However, delegates (C#), anonymous classes (Java) and function pointers (C) don't quite qualify because the following also needs to be true:
- Closures need to be able to refer to variables already present in scope at the time they're defined.
- Closures shouldn't require complex syntax (I personally think this point is a tad subjective).
PHP's upcoming syntax for closures is shaping up to be comparable to the C# 2.0 implementation. In the .NET world closures first arrived as anonymous methods in C# 2.0 (these were later simplified into lambda expressions in C# 3.0).
For comparison's sake C# anonymous methods look something like this:
/* Returns true if tOne and tTwo are both evenlyWhen released, a comparable implementation in PHP 5.3 will probably look something like the following:
divisible by the denominator (denom) */
public bool EvenlyDivisible(int denom, int tOne, int tTwo)
{
//Define the closure
PredicateevenlyDivisible = delegate(int testNum)
{
//Note that denom is defined outside closure scope
if ((testNum % denom) == 0)
{
return true;
}
else
{
return false;
}
};
//Use the closure as necessary
if (evenlyDivisible(tOne) && (evenlyDivisible(tTwo)))
{
return true;
}
else
{
return false;
}
}
/* Returns true if $tOne and $tTwo are both evenlyFor additional information please check out the closure proposal on php.net.
divisible by the denominator ($denom) */
function EvenlyDivisible($denom, $tOne, $tTwo)
{
$evenlyDivisible = function ($testNum) use ($denom) {
//Note that $denom is defined outside closure scope
if (($testNum % $denom) == 0)
{
return true;
}
else
{
return false;
}
};
//Use the closure as necessary
if ($evenlyDivisible($tOne) && ($evenlyDivisible($tTwo)))
{
return true;
}
else
{
return false;
}
}