DEV Community

Chonbashev Artyk
Chonbashev Artyk

Posted on

Functional Programming in PHP: Part 2

First part

Today we will cover: First Class and High Order Functions.

So, now we know what is a pure function, what else do we need to know?
In PHP we have a First Class Function, what is it and how to use it?

First Class Function means, we can use our function like any other types.
For example, we can pass it around, we can assign it, destroy, etc.

Let's see an examples:

// Assign
$validate = fn(string $x): bool => strlen($x) > 14;

// Destroy
unset($validate);

// Pass it
$id = fn($x) => $x;

function map(callable $fn, array $arr): Generator {
    foreach($arr as $item) {
        yield $fn($item);
    }
}

$fruits = ['apple', 'orange'];
$unchangedFruits = map($id, $fruits); // ['apple', 'orange'];
$capitalizedFruits = map('ucfirst', $fruits); // ['Apple', 'Orange'];

So, now we know, that we can use our functions like everything else, that's great!
And now get to know what is High Order Functions, that's a function which accepts a function and/or returns a functions! So, that's basically our map function above :)

So, let's see how does it look, when function returns a function.

// Change our function a little
function map(callable $fn): callable {
    return function(array $arr) use($fn): Generator {
        foreach($arr as $item) {
            yield $fn($item);
        }
    }     
}

$doube = map(fn($x) => x * 2);
$doube([1, 2, 3]); // 2, 4, 6

What benefits we gained?
Well, now we have a function which work with arrays and can easily return to us our function which will work with any array and double it, so we can easily reuse our High Order map and First Class double function :)

Top comments (0)