DEV Community

Chonbashev Artyk
Chonbashev Artyk

Posted on

2

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 :)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️