Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 815
Uri Goren Avatar asked Oct 10 '14 09:10

Uri Goren


People also ask

What is pure function in PHP?

A pure function is a function that, given the same input, will always return the same output and are side-effect free. // This is a pure function function add($a, $b) { return $a + $b; } Some side-effects are changing the filesystem, interacting with databases, printing to the screen.

What is a pure function?

In computer programming, a pure function is a function that has the following properties: the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams), and.

What is pure function with example?

A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc.


1 Answers

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.

like image 180
9072997 Avatar answered Oct 08 '22 14:10

9072997