Gen. partnerAlgotech

Pure functions in PHP

Example of a pure function:

|
October 27, 2021

In functional programming, there is a concept of a pure function, which refers to a function that always returns the same output to the same input (i.e. is deterministic), and at the same time does not suffer from any side-effects (i.e. does not affect its environment).

What a pure function looks like

Example of a pure function:

// This is a pure function
function add(int $a, int $b): int
{
return $a + $b;
}

This is a pure function because the output is always the same based on the input arguments.

What is not a pure function

// This is an impure function
function add(int $a, int $b): int
{
echo 'Adding...';
file_put_contents('file.txt', 'value: ' . $a);
return $a + $b;
}

This type of function is not pure because the function changes the file system. Another type of impure function is when it interacts with the database, prints to the screen, and so on.

Loading comments...

Stay in the loop

Subscribe to our newsletter and get the latest cybersecurity news delivered straight to your inbox.

Your data is safe. You can unsubscribe from the newsletter at any time.