Pure functions in php

Pure functions in php

As per wiki, pure function is the one with following characteristics:

  • Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).
  • Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).
    Thus a pure function is a computational analogue of a mathematical function. Some authors, particularly from the imperative language community, use the term “pure” for all functions that just have the above property.

I am trying to translate that to PHP. Here are the thoughts I have on pure functions:

  • All arguments are passed by value and not by reference.
    • No arguments with &
    • No objects passed as arguments as objects are passed by reference
  • They don’t access state of the class
    • They don’t access anything with $this
  • The don’t access global or super globals
    • They don’t use $_ variables
    • They don’t have global keyword
  • They don’t access I/O, network calls, etc.
    • No file operations
    • No network calls, database calls, etc.
  • They don’t have static calls
    • When there are static calls, their results may change
  • There are no side effects
    • State of the class shouldn’t change, i.e., it should’t update members of the class
  • Output is solely dependent on input

Let me know your thoughts and correct me if I am missing something.

2 Comments on “Pure functions in php”

  1. when an object is supplied as an input, i consider that the function stays technically pure if i am sure that the way i use the provided object does not modify the outer world or the object itself.

Leave a Reply

Your email address will not be published. Required fields are marked *