Pure Functions
Learn about pure functions, their side causes, and their side effects.
What’s a pure function?
A pure function is one free from side effects and side causes. Side effects and side causes are either caused by or cause undesirable state changes in scopes both local and foreign to a function definition.
Side causes and side effects
A side cause is a product of impure input. It’s typically an input, such as a global variable used in a function body or an ORM (object-relational mapper) object specified as a function parameter. A side effect i is the result of impure functions. Side causes often cause side effects.
Problem 1
Look closely at the following code snippet:
<?php$counter = 0;function increment(){global $counter;$counter++;return $counter;}increment(); // increments the value of the counter variableecho $counter; // outputs 1
In the case above, the increment
function utilizes the global counter
variable. Each call to the increment
function assigns a new value to the counter
variable, producing new output. The undesirable side effect in this scenario is an increase in the value of the global counter
variable, and the side cause is using the globally scoped counter
variable in the increment
function definition.