O'Reilly logo

Functional PHP by Gilles Crettenand

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Referential transparency

An expression is said to be referentially transparent if you can substitute it by its output at any time without changing the behavior of your program. In order to do that for all expressions of your code base, all your functions have to be pure and all your variables have to be immutable.

What do we gain from referential transparency? Once again, it helps a lot with reducing cognitive burden. Let's imagine we have the following functions and data:

<?php // The Player implementation is voluntarily simple for brevity. // Obviously you would use immutable.php in a real project. class Player { public $hp; public $x; public $y; public function __construct(int $x, int $y, int $hp) { $this->x = $x; $this->y = $y; $this->hp = $hp; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required