Is PHP a functional programming language?

So you think PHP is a functional programming language? Let's look at reasons why it is and why it isn't.

When I first learned to write code, I didn’t understand what functional programming really was. I knew PHP. I knew JavaScript. Both languages used functions, and a number of books called them functional, so I assumed they were both functional programming languages.

That assumption was misguided.

As a kid, I’d learned to write QuickBASIC with my father. It was a great exercise, and we had a blast copying simple programs – by hand – from the back of books into our computer. Our programs were filled with “sub-routines” to make code reusable.

These blocks of resuable code were not called functions and QuickBASIC was clearly not a functional programming language. Those two differences cemented in my mind what I would and wouldn’t consider functional programming later in my career.

Defining functional programming

There are three concepts important to functional programming:

  1. Higher-order functions. You need to be able to define functions in userland in the first place. On the surface, this seems obvious as we can do so already in both PHP and JavaScript. But the ability to use a function keyword to define custom code alone does not make a language “functional.”
  2. First-class functions. Once you’ve defined a function, you can assign this function to a variable and pass it into another function as a parameter. This capability empowers you to compose multiple functions together and build an even more powerful and flexible program.
  3. Pure functions. Functions receive input and return a value, but variable are otherwise immutable. There are no side-effects triggered by calling a function (changing a variable value, writing to disk, etc).

Any functional programming language must not just support all three of these concepts. That language needs to emphasize these concepts. It must, by default, focus on functions as the primary means of programming and remove the option of mutability to ensure the purity of data.

PHP allows you to write in a functional programming style. But PHP does not force that paradigm on you. In fact, PHP supports multiple, distinct programming paradigms by default.

What’s the verdict?

To summarize, no, PHP is not a functional programming language.

At the same time, yes, it is a functional programming language.

As a multi-paradigm language, PHP gives the developer the ability to decide if they want to use PHP functionally, or procedurally, or as a mix of both.

If you want to learn the best way to focus on functional programming in PHP, there are several books on the topic. Pick one up and dive in!