Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. The key principles include:
Immutability is a cornerstone of functional programming. When data is immutable:
Example:
// Imperative approach (mutable)
$numbers = [1, 2, 3];
$numbers[] = 4; // Modifies original array
// Functional approach (immutable)
$numbers = ImmList(1, 2, 3);
$newNumbers = $numbers->append(4); // Creates new list, original unchanged
Algebraic Data Types (ADTs) provide a way to compose complex data types from simpler ones. They come with mathematical laws that guarantee behavior:
Option = Some(value) | None
Either = Right(value) | Left(error)
Pair<A,B> = Pair(valueA, valueB)
These types follow specific laws:
By adhering to these laws, we can reason about our code with confidence. In practice, this means that we can use algebraic types to model our data and functions reliably, and we can use laws to test our code.
Here is an example of testing a implementation of Option using the laws of associativity and identity:
$some = Option(10);
$none = Option(null);
// Associativity
assert($some->map(fn($x) => $x * 2)->map(fn($x) => $x + 1) === $some->map(fn($x) => $x * 2 + 1));
assert($none->map(fn($x) => $x * 2)->map(fn($x) => $x + 1) === $none);
// Identity
assert($some->map(fn($x) => $x) === $some);
assert($none->map(fn($x) => $x) === $none);
While PHP wasn’t designed as a functional language, it supports many functional concepts:
However, PHP lacks some FP features out of the box:
Phunkie brings functional programming concepts to PHP in a practical way:
$maybeUser = Option(findUser($id));
$userName = $maybeUser
->map(fn($user) => $user->name)
->getOrElse("Guest");
Phunkie strives to:
By adopting Phunkie’s approach, you can gradually introduce functional programming concepts into your PHP applications while maintaining readability and reliability.