Every PHP programmer grows up eventually. Here's the same function, factorial(6), as written at each stage of the journey.
<?php
// Newbie programmer
function factorial($x) {
if ($x == 0) {
return 1;
} else {
return $x * factorial($x - 1);
}
}
echo factorial(6);
<?php
// PHP 4 veteran
$n = 6;
function factorial() {
global $n, $result;
$result = 1;
for ($i = 1; $i <= $n; $i++) {
$result = $result * $i;
}
}
factorial();
echo $result;
<?php
// Copied it from a forum in 2003
$n = @$_GET['n'] ? @$_GET['n'] : 6; // TODO: validate input??
$f = 1; for ($i = 2; $i <= $n; $i++) $f *= $i;
echo "<b>" . $f . "</b>";
<?php
// Discovered design patterns
interface FactorialStrategy {
public function calculate(int $n): int;
}
class IterativeFactorialStrategy implements FactorialStrategy {
public function calculate(int $n): int {
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
}
class FactorialStrategyFactory {
public static function create(): FactorialStrategy {
return new IterativeFactorialStrategy();
}
}
echo FactorialStrategyFactory::create()->calculate(6);
<?php
// Modern PHP 8 developer
declare(strict_types=1);
function factorial(int $n): int {
return match (true) {
$n <= 1 => 1,
default => $n * factorial($n - 1),
};
}
echo factorial(6);
<?php
// Functional PHP developer
echo array_reduce(range(1, 6), fn($carry, $i) => $carry * $i, 1);
<?php
// EXPERT PROGRAMMER
echo array_product(range(1, 6));
See also: the evolution of a Python, Ruby, JavaScript, C or Perl programmer, and where this joke started, Fritz Ruehr's The Evolution of a Haskell Programmer (itself a riff on the old "Hello World" Evolution of a Programmer).