Currying

Currying is a technique of transforming a function that takes multiple arguments to a chain of functions where each function will take exactly one argument. In other words, if a function can be written as f(x,y,z), then the currying version of this will be f(x)(y)(z). let's consider the following example:

function sum($a, $b, $c) {
return $a + $b + $c;
}

Here, we have written a simple function with three parameters and when called with numbers, it will return sum of the numbers. Now, if we write this function as a curry, it will look like this:

function currySum($a) { 
return function($b) use ($a) {
return function ($c) use ($a, $b) {
return $a + $b + $c;
};
};
}

$sum = currySum(10)(20)(30);

echo $sum;

Now if we run the currySum as a currying function, we will get the result 60 for the preceding example. This is a very useful feature for functional programming.

Earlier, it was not possible to call a function like f(a)(b)(c) in PHP. Since PHP 7.0, Uniform Variable Syntax allows immediate execution of a callable, as we saw in this example. However, to do this in PHP 5.4 and higher versions, we would have to create temporary variables in order to store the lambda functions.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset