O'Reilly logo

Functional PHP by Gilles Crettenand

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Currying

Currying is often used as a synonym for partial application. Although both concepts allow us to bind some parameters of a function, the core ideas are a bit different.

The idea behind currying is to transform a function, taking multiple arguments into a sequence of functions taking one argument. As this might be a bit hard to grasp, let's try to curry substr function. The result is called a curryied function:

<?php 
 
function substr_curryied(string $s) 
{ 
    return function(int $start) use($s) { 
        return function(int $length) use($s, $start) { 
            return substr($s, $start, $length); 
        }; 
    }; 
} 
 
$f = substr_curryied('Lorem ipsum dolor sit amet.'); 
$g = $f(0); 
echo $g(5); 
// Lorem 

As you can see, each call returns a new function that takes the next parameter. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required