Functional programming in PHP

If you’re been reading along over the past few months, you would’ve undoubtedly picked up on my fascination towards functional programming (FP). While PHP is not stereotypical known for its FP prowess, version 5.3 introduced a nice palette of FP functionality.

In what would hopefully be the start of a series of articles, I would like to show you how you can use the FP facilities available in the language to write expressive and elegant code.

In PHP 5.3, functions were upgraded to first-class citizens in the language. This means that functions can be passed around as values.

Here’s an example.

$incrByTwo = function($n) {
    return $n + 2;
};

echo $incrByTwo(5);         // 7
echo $incrByTwo(10);        // 12
echo get_class($incrByTwo); // Closure

When you create an anonymous function, PHP gives it the type Closure. Closures have their own scope, which allows for nice modular code.

$name = "John";

$greet = function($name) {
    return "Hello, " . $name;
};

echo $name;          // "John"
echo $greet("Mary"); // "Hello, Mary"
echo $greet($name);  // "Hello, John"

Here are some examples of anonymous functions in PHP.

A function that check if the value is an even number:

$isEven = function($n) {
    return ($n % 2 == 0);
};

echo $isEven(2); // True
echo $isEven(3); // False

A function that returns the square of the value given:

$square = function($x) {
    return $x * $x;
};

echo $square(2); // 4
echo $square(8); // 64

A function that multiplies the first value by the second value:

$multiply = function($x, $y) {
    return $x * $y;
};

echo $multiply(2, 3); // 6
echo $multiply(3, 9); // 27

A function that returns the sum of all its arguments:

$sum = function() {
    $args = func_get_args;
    $sum  = 0;
    foreach ($args as $k => $v) {
        $sum += $v;
    }
    return $sum;
};

echo $sum(5, 6, 7, 8); // 26
echo $sum();           // 0
echo $sum(5, 6);       // 11

So there you have it. Your very first anonymous functions in PHP. As homework, have a go at writing the following functions.

echo $isOdd(1); // True
echo $isOdd(6); // False

echo $cube(2); // 8
echo $cube(3); // 27

echo $subtract(7, 2); // 5
echo $subtract(2, 6); // -4

echo $multiply();      // 1
echo $multiply(2,3);   // 6
echo $multiply(4,5,6); // 120

Subsequent entries will be published under the php-fp-series category for your bookmarking convenience. Till next time, happy coding!

One Reply to “Functional programming in PHP”

Comments are closed.