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.

Answer from 9072997 on Stack Overflow
🌐
Rip Tutorial
riptutorial.com › pure functions
PHP Tutorial => Pure functions
YAML in PHP · Bulk Insert · Bulk Delete · Bulk Update · Bulk Merge · A pure function is a function that, given the same input, will always return the same output and are side-effect free.
Discussions

How to increase the number of pure functions in your code
That doesn't sound like a valid goal. You can increase number of pure functions and end up with even more shitty code. Static analisys can somewhat validate code quality, but it will not magically emerge from fulfilling its constraints - it would be much easier to understand the concepts behind them. Side effects should be pushed out of application core (top or botom in the control flow), but you still need them unless you're writing a calculator app. You might not need mocking to test individual functions, but you will test them as a part of larger units that require mocking anyway. Also composability implies that you need first-class and higher order functions - you might want to mock those callable parameters as well or you will have to test all possible compositions. If you use named (static) functions composability becomes hell because you will be passing string/array (callable) parameters around with no IDE support (as if it wasn't bad enough for anonymous functions). Theoretically you can achieve OOP modularity by including procedural files with conditionally resolved string variables. It all seems like misunderstood concepts or confused paradigms, where procedural approach to functions is justified with advantages of functional programming in the context of uncertain comprehension of OOP. More on reddit.com
🌐 r/PHP
26
6
November 4, 2019
Pure methods - where to put 'em?
Feel free to use functions in namespaces. More on reddit.com
🌐 r/PHP
67
2
October 30, 2019
Infer function/method as `@pure` without the need to mark it explicitly
Functionally pure operations have invariant properties that make systems simple to reason about, and enforcing @pure constraints is extremely powerful: entire programming languages have been designed around this, since the concept is so powerful. ... have developers implement it, having them respect the given @pure constraint via PHPStan... More on github.com
🌐 github.com
5
January 9, 2025
php - What is the "Add #[Pure] attribute" inspection in PhpStorm checking for? - Stack Overflow
As soon as a method changes, or ... be Pure. 2021-12-30T12:32:01.87Z+00:00 ... It's essentially a form of documentation (it's just in a format that's intended to be used by the IDE rather than for direct human consumption). So if you change the behavior of a function you need to keep it consistent. 2021-12-30T15:20:24.753Z+00:00 ... Use this attribute for functions that do not produce any side effects. All such PHP internal functions ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Educative
educative.io › learn functional programming in php › pure functions
Pure Functions
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.
🌐
Olleharstedt
olleharstedt.github.io › programming › php › 2023 › 04 › 11 › strategies-to-make-functions-pure-php.html
Strategies to make functions pure
April 11, 2023 - foo(...) in PHP is actual syntax to return a first-class callable for a function. ↩ · In functional programming you can use the IO monad pattern to make effectful code pure, but it really only makes sense when the programming language supports monadic syntax.
🌐
Brj
en.php.brj.cz › pure-functions-in-php
Pure functions in PHP
October 27, 2021 - This is a pure function because the output is always the same based on the input arguments.
🌐
Medium
medium.com › swlh › functional-programming-in-php-why-not-291ded3a3bec
Functional programming in PHP : Why not ? | The Startup
August 18, 2020 - BUT, when passing objects the value passed to the function is the object’s handle (which acts as a reference to the object), so to write pure functions that accepts objects as parameter, you must only read objects and not modify them ! And on that too, PHP is not helping, because it includes in its standard library a lot of impure functions !
🌐
Programming-books
programming-books.io › essential › php › pure-functions-be14cd23d7b443c08dd72abfd7424f56
Pure functions
Essential PHP · suggest change · 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 ...
🌐
Reddit
reddit.com › r/php › how to increase the number of pure functions in your code
r/PHP on Reddit: How to increase the number of pure functions in your code
November 4, 2019 -

Pure functions have lots of desirable properties, for example:

  • Composability (without side-effects, you can combine them freely)

  • Predictability (clear relation between input and output)

  • Nothing to mock when testing (all dependencies are in the input variables)

  • Nothing to mock when they are used (since mocking is mostly done to control side-effects, pure functions can often be used as-is)

Because of this, we want to increase the number of pure functions in our code-base and reduce the number of functions and classes that has side-effects. But how? Here are some ways:

  • Move side-effects up in the stack-trace to separate calculations from file IO, database access, etc (e.g. only call classes with side-effects from controller methods if using MVC)

  • Use value objects with no methods and no setters instead of traditional OOP; these objects are also immutable

  • Use explicit state instead of implicit (kind of the same as above; state is part of function input and passed around)

  • Use annotations to keep functions pure, e.g. Psalm's @psalm-pure (https://psalm.dev/docs/annotating_code/supported_annotations/#psalm-pure)

  • If a method has no this nor self, move it to a pure function instead

In PHP, there are also some downsides:

  • Pure functions cannot be hidden/encapsulated (no module system), so the API will be polluted. Static methods could resolve this, but it muddles the intent of the code since static methods are often used for singleton factories etc (BUT: Not if you use @psalm-pure annotations?)

  • You cannot use inheritance for code reuse (BUT: Maybe better to use composition and interfaces instead anyway?)

  • Code could look unorthodox and become harder to read and maintain (this is PHP, not Haskell)

  • PHP is a language for the web, and the web is mostly about shuffling data from here to there, that is, state-full computations

  • More...?

Some things to think about:

  • Should a project's folder structure reflect side-effect-free vs side-effect-full code?

  • How to educate colleagues about pros and cons of pure functions?

  • Real example needed of how to convert state-full code to pure

  • More...?

Do you have any thoughts or something to add?

Thanks for reading!

Edit: Some further reading:

  • https://sidburn.github.io/blog/2016/03/14/immutability-and-pure-functions

  • https://old.reddit.com/r/PHP/comments/dp5pcb/pure_methods_where_to_put_em/

Top answer
1 of 3
10
That doesn't sound like a valid goal. You can increase number of pure functions and end up with even more shitty code. Static analisys can somewhat validate code quality, but it will not magically emerge from fulfilling its constraints - it would be much easier to understand the concepts behind them. Side effects should be pushed out of application core (top or botom in the control flow), but you still need them unless you're writing a calculator app. You might not need mocking to test individual functions, but you will test them as a part of larger units that require mocking anyway. Also composability implies that you need first-class and higher order functions - you might want to mock those callable parameters as well or you will have to test all possible compositions. If you use named (static) functions composability becomes hell because you will be passing string/array (callable) parameters around with no IDE support (as if it wasn't bad enough for anonymous functions). Theoretically you can achieve OOP modularity by including procedural files with conditionally resolved string variables. It all seems like misunderstood concepts or confused paradigms, where procedural approach to functions is justified with advantages of functional programming in the context of uncertain comprehension of OOP.
2 of 3
2
Composition + higher order functions = strategy pattern. Partial application = DI. There are plenty of equivalencies. Just don't tell Java fanboys. They will get heart attack at suggestion that array_map is good example of OCP of SOLID game;) Hard limitation of php is lact of function signature beyond "it can be executed" truism. This is really, really annoying and require extra effort to get things as we want them.
Find elsewhere
🌐
Reddit
reddit.com › r/php › pure methods - where to put 'em?
r/PHP on Reddit: Pure methods - where to put 'em?
October 30, 2019 -

Pure functions have lots of pros. They are predictable, composable, testable and you never have to mock them. Thus, we should try to increase the number of pure methods/functions in our code base, right? So how would you do that? If you have a method with both side-effects and calculations, you can sometimes life the side-effects out of the method. That is why lifting side-effects higher up in the stack trace will increase white-box testability. Taken to the extreme, you end up with a class with only properties, and a bunch of functions that operate on that class, which is close to functional programming with modules and explicit state (although you lose encapsulation).

Anyway, you have a class, you have a bunch of methods, you realize some could be made pure easily. Would you do it? In MVC, would you create a helper namespace and put your pure functions there? Or is this just an empty intellectual exercise with no real-world applicability?

🌐
SitePoint
sitepoint.com › blog › php › functional programming and php
PHP Master | Functional Programming in PHP
November 11, 2024 - A function is said to be free from side effects if it does not change the value of an object outside itself, such as a global or static variable, and does not have any I/O effects like writing into file, database, and so on. Such functions are otherwise called pure functions.
🌐
TechDiscuss
techdiscuss.net › home › refactoring
Pure functions in php | TechDiscuss
March 3, 2021 - 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).
🌐
Pontis Technology
pontistechnology.com › home › what are functional programming building blocks in php – part 1
Functional programming building blocks in PHP - Pontis Technology
October 28, 2024 - In this series of articles, we ... about concept of: ... Pure functions are functions that have deterministic behaviour – they always produce the same output for the same input....
🌐
GitHub
github.com › phpstan › phpstan › issues › 12402
Infer function/method as `@pure` without the need to mark it explicitly · Issue #12402 · phpstan/phpstan
January 9, 2025 - Functionally pure operations have invariant properties that make systems simple to reason about, and enforcing @pure constraints is extremely powerful: entire programming languages have been designed around this, since the concept is so powerful. ... have developers implement it, having them respect the given @pure constraint via PHPStan, transitively
Author   Ocramius
🌐
Sal Ferrarello
salferrarello.com › home › pure functions – the secret to writing easily testable code
Pure Functions - The Secret to Writing Easily Testable Code - Sal Ferrarello
June 1, 2024 - A pure function is a function where we can accurately predict the return value based on the arguments passed into it.* The built-in PHP function strrev() reverses a string. This is a pure function.
🌐
Leanpub
leanpub.com › functional-php › read
Functional PHP
Learn to use functional programming to write more concise and succinct PHP code that works and scales as the complexity of your application does
🌐
GitHub
github.com › php-static-analysis › attributes › blob › main › doc › Pure.md
attributes/doc/Pure.md at main · php-static-analysis/attributes
This attribute is the equivalent of the @pure annotation for class methods and functions. The attribute accepts no arguments. <?php use PhpStaticAnalysis\Attributes\Pure; class PureExample { #[Pure] // this function is pure public static function add(int $left, int $right) : int { return $left + $right; } ...
Author   php-static-analysis