Pure vs impure PHP functions

Pure functions

  • There are no globals and values are not passed by reference
  • They have no side effects
  • They dont use loops (for, for each, while…)

Impure functions

  • Mutate global state
  • May modify their input parameters
  • May throw exceptions
  • May perform any I/O operations: i.e. external resources (databases, network, file system…)
  • May produce different results even with the same input parameters.
  • May have side effects

Pure functions

always return the same output given the same input.

function add(int $a, int $b) : int
{
  return $a + $b; //should return a sum of $a and $b
}

Impure functions

A function whose return value is one modified outside of its scope is considered impure. All functions whose return values are contingent on the return values of functions like date() and random() as well as those dependent on global variables and file interactions are impure.


$counter = 0;

function inc() {
  global $counter;
  return $counter++; //the global variable renders this impure
}

function timeAdvance() {
  return time() + 5; //returns a new value every time it is run
}

function dbUpdate($orm, $value) {
  return $orm
    ->update('some query', $value)
    ->execute();
} //interacts with a database and is impure