Pure functions in PHP

📅   27. 10. 2021
👤   Jan Barášek

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.

Jan Barášek     More about the author

The author works as a senior developer and software architect in Prague (Czech republic, Europe). He designs and manages large web applications that you know and use. Since 2009 he has gained a wealth of experience which he passes on through this website.

I'd be happy to help:

Contact