Function Composition in PHP

Function composition

The practice of chaining function calls, or composition, is common in functional programming. In fact, the spirit of functional programming is composition. A function chain is a nest of functions and, like any series, follows a linear chronology. In a function chain, the output of one function serves as input for the next. This concept is rooted in mathematics, where two functions, f(x)f(x) and g(x)g(x), can be composed to create a new function, f(g(x))f(g(x)), or fgf \circ g.

f(x)=x+1f(x) = x + 1

g(x)=x2g(x) = x^2

fg=x2+1f \circ g = x^2 + 1

Function composition in PHP can be approached in one of two ways:

  1. Traditional style
  2. Point-free style

The first style is quite popular and reflects a composition one may not be aware of at first. The second style enforces more compact function definitions and more recognizable chains.

Get hands-on with 1200+ tech skills courses.