DEV Community

Chonbashev Artyk
Chonbashev Artyk

Posted on

3 2

Functional Programming in PHP

Hello there!
I decided to write a little bit about FP which I know.

This time we will talk about Functional Programming
and one of it's concepts Pure Functions.

So, let's start what is Functional Programming itself?
As you can guess it's based upon functions and not which we are used to,
but math functions and the biggest difference here's the all math functions are pure and have a single argument.

So let me give an example:

function hello(string $name): string {
    return "hello, $name!";
}

This function is pure, because it has following:

  1. It doesn't have side effects
  2. It's referentially transparent

What is a side effect? It's something that's done outside of scope of our function, e. g.: database queries, file writings, changing global variable values, etc. Example (to run in cli):

function hello(string $name): void {
    echo "Hello, $name!";
}
hello('John'); // John
fclose(STDOUT);
hello('John'); // Nothing

So now we know, at least our function must not change state of our app to be pure,

What is RT? It's when our function depends on it's input (arguments) and produce the same output if you have given the same arguments.
And the first introduced function is referentially transparent, because no matter how many times we call it with the same arguments, we will receive the same result.

function hello(string $name): string {
    return "hello, $name!";
}

hello('John') // John
hello('John'); // John

What benefits we gain?

  1. Easy to test
  2. Easy to understand

If somebody is interested in it, I will continue to cover this topic.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
iquardt profile image
Iven Marquardt

A pure function

  • must not have any effects than returning a result value (RT)
  • must return the same output for the same input (deterministic)
  • must always return a value no matter what input is provided (total function)
Collapse
 
asiros profile image
Chonbashev Artyk

Thank for addition, appreciate this! :)

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. ❤️