'PHP Pure functions

I am trying to identify pure functions in PHP code.

A pure function is one where both these statements about the function hold:

  • The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  • Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

(definition from Wikipedia)

Is it sufficient to say that a PHP function is pure if and only if

  • all its arguments are passed by value (no & in the argument list)
  • it does not use object members (no $this in the function body)
  • it does not use globals (it doesn't contain global in the function body)
  • it does not use superglobals (it doesn't contain $_ variables)

Are these statements true ? Am I missing any use cases ?



Solution 1:[1]

You are missing a lot of use-cases

  • rand()
  • database interaction
  • file IO
  • static variables
  • calls to other functions with global
  • import/require statements inside functions
  • functions with internal state like ob_get_contents()
  • mutating array pointers

There is probably a lot of stuff I'm not thinking of. PHP has a very stateful design.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 9072997