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;
}
}
2 comments:
Not requiring a complex syntax is a tad subjective indeed, but I personally consider it to be very important. Half of the reason why closures are so useful to me (in those languages that support them well) is that they make it much easier to read and understand the program. Something that could normally be written in three lines and a four-line function definition without closures is not going to get any better if it takes twice as much space and uses some fancy extra instructions.
thank u r information
it very useful
u r blog Is very nice
Post a Comment