TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

PHP functional programming for beginner

In this article, we are going to introduce a new programming paradigm called functional programming. This is an introductory article.

The definition

In this article, we will start from the definition of functional programming, analyze its key characteristics and demonstrate them in PHP source code. At the end of this article, you should be able to understand the fundamentals of functional programming and use it in your future projects.

First thing first, the excerpts as shown below from wikipedia gives us a clear definition of functional programming:

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead of statements. ... Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

In our opinion, three key characteristics of functional programming are:

  • Embrace immutability
  • Declarative programming
  • Avoid Side-effects

Embrace immutability

An object that cannot be changed after is creation is an immutable object. The first common question would be what the benefits of immutable objects are.

In fact, immutable object is considered a better way of managing objects comparing to mutable object in general. By using immutable object, we get consistent object through its life cycles. In simple terms, we place validations or checks in the constructor of immutable object to make sure it is valid right from the start. No setters should be created for immutable object, so that its state can never be changed. And we return a copy of it whenever we need to alter an immutable object.

Code as shown below is an example of an immutable object in PHP:

final class EmailAddress
{
    private $mailbox;
 
    private $host;
 
    public function __construct($email)
    {
        if (false === strpos($email, '@')) {
            throw new \InvalidArgumentException('Invalid email');
        }
        list($this->mailbox, $this->host) = explode('@', $email);
    }
 
    public function __toString()
    {
        return sprintf('%s@%s', $this->mailbox, $this->host);
    }
 
    public function changeMailbox($newMailbox)
    {
        $copy = clone $this;
        $copy->mailbox = $newMailbox;
        return $copy;
    }
}

In the code example above, validation of an email address is placed inside the constructor, once a EmailAddress is created, we are confident it is always valid. This avoid us from checking the string format all over the places.

Understanding declarative programming

We were taught to implement algorithm using basic coding blocks such as loops and conditionals when we started programming. This is called imperative programming, in which we describe each step a program must take to accomplish a task.

For example, to convert array of string to uppercase in PHP, we would normally implement a loop as shown below:

$names = ['mike', 'jordan', 'david'];
foreach($names as $i=>$name) {
   $names[$i] = strtoupper($name);
}

As opposite to imperative programming, we solve a problem by applying a set of functions to the problem set.

To solve the same problem above using declarative programming in PHP, we can do:

$names = array_map('strtoupper', $names);

Some key difference between imperative programming and declarative programming are:

  • Imperative programming focuses on the algorithms whereas declarative programming focuses on input and output of a function.
  • No state changed in declarative programming whereas in imperative programming, state change is common.

Understanding side-effects

There is a long and detailed explanation for side-effects in programming on wikipedia.

In our opinion, we can think of side-effects as implicitly changing something somewhere. Implicitness is the nature of side-effects, in this case, there is no way other than looking into implementation of a piece of code to find out what it changes.

Let's demonstrate side-effects in code samples.

To get the first element of an array in PHP, we can use the built-in array function array_shift:

$names = ['mike', 'jordan', 'david'];
 
echo array_shift($names);
 
// Output
mike

Does function array_shift come with side-effect? Let's output the original array after applying it:

$names = ['mike', 'jordan', 'david'];
 
echo array_shift($names);
 
print_r($names);
 
// Output
mike
 
(
[0] => jordan
[1] => david
)

As we can see above, function array_shift does have side-effect. It modifies the original array without us knowing it.

A function that accepts an input and always return a predictable output is called pure function. Pure functions have no side-effects, embrace immutability and enable us develop with declarative programming style.

The End

Hope you have enjoyed this tutorial and learned something useful for your next project. If you have any questions or you have some suggestions for us, do leave a comment below. Lastly sharing is caring, please share this tutorial to help it reach more audiences.

Hopefully this simple tutorial helped you with your development . If you like our post, please follow us on Twitter and help spread the word . We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know .