Need to upgrade to the latest version of Laravel? Get instant, automated Laravel upgrades with Laravel Shift

PHP in 2020

It's no secret among web developers and programmers in general: PHP doesn't have the best reputation. Despite still being one of the most used languages to build web applications; over the years PHP has managed to get itself a reputation of messy codebases, inexperienced developers, insecure code, an inconsistent core library, and what not.

While many of the arguments against PHP still stand today, there's also a bright side: you can write clean and maintainable, fast and reliable applications in PHP.

In this post, I want to look at this bright side of PHP development. I want to show you that, despite its many shortcomings, PHP is a worthwhile language to learn. I want you to know that the PHP 5 era is coming to an end. That, if you want to, you can write modern and clean PHP code, and leave behind much of the mess it was 10 years ago.

So let's look at how the language has changed, matured even, over the past few years. I want to ask you to set aside any prejudice for just a few minutes, and possibly be surprised by what PHP is today.

Let's dive in.

Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what's happening on this blog, you can subscribe to my mailing list: send an email to brendt@stitcher.io, and I'll add you to the list.

# History summarized

Before diving into details, let's review how PHP, the language, is developed these days. We're at version 7.4 now, and PHP 8 will be the next version after that, at the end of 2020.

Ever since the late 5.* era, the core team tries to keep a consistent yearly release cycle, and have succeeded in doing so for the past four years.

In general, every new release is actively supported for two years, and gets another year of "security fixes only". The goal is to motivate developers to stay up-to-date as much as possible: small upgrades every year are easier than making the jump between 5.4 to 7.0, for example.

Lastly, PHP 5.6 was the latest 5.* release, with 7.0 being the next one. If you want to know what happened to PHP 6, you can listen to this episode of the PHP Roundtable podcast.

PHP's development these days is done by a group of volunteers, some of them are paid by their employers to work on the core full time. Most discussion of how the language is evolved happens on a mailing list.

With all of that out of the way, let's debunk some common misconceptions about modern PHP.

# PHP's type system

PHP started out as a very weakly and dynamically typed language, which had its benefits at the time. Ever since people started to use PHP for larger projects though, the shortcomings of its type system became clear, and the need for stronger type support arose.

Today, PHP is a rather unique language: it still allows you to write completely dynamically and weakly typed code, but also has a much stronger, opt-in type system. Combined with static analysis, tools like Psalm, Phan and PHPStan, you can write secure, strongly typed and statically analysed code.

Take, for example, a look at this snippet of PHP code, using its modern type system in full:

<?php

declare(strict_types=1);

final class Foo
{
    public int $intProperty = 2;

    public ?string $nullableString = null;

    private Bar $bar;

    public function __construct(Bar $bar) {
        $this->bar = $bar;
    }
    
    public function withInt(int $value): self
    {
        $clone = clone $this;
    
        $clone->intProperty = $value;

        return $clone;
    }
    
    public function unionTypes(int|float $input): void
    {
        // Union types will be added in PHP 8
    }
}

Truth be told, there's one important feature still missing in PHP's type system: generics. There's hope they will be added, but there's nothing concrete yet. In case of typed arrays, you'll need to rely on docblocks to get proper IDE support:

/** @var int[] */
public array $arrayOfInts = [];

And while typed arrays are a common use case for generics, solvable with docblocks, there's a lot more functionality we're missing out on because they are not in the language… yet.

# PHP's syntax

The 7.* era has done many good things in terms of making PHP a more mature language when it comes to syntax. To illustrate this I've made a non-exhaustive list of new things in PHP.

Array destructuring:

[$a, $b] = $array;

The null coalescing operator:

$value = $object->property ?? 'fallback if null';

$value = $array['foo'] ?? "fallback if key doesn't exists"; 

The null coalescing assignment operator:

public function get(string $input): string 
{
    return $this->cache[$input] ??= $this->sanitize($input);
}

Array spreading:

$a = [/* … */];
$b = [/* … */];

$mergedArray = [...$a, ...$b];

Variadic functions:

public function get(Foo ...$foos): void
{
    foreach($foos as $foo) {
        // …
    }
}

Argument unpacking:

$this->get(...$arrayOfFoo);

Typed properties:

public int $intProperty;

Arrow functions, also called short closures:

$ids = array_map(fn(Post $post): int => $post->id, $posts);

Generators:

function make(array $input): Generator
{
    foreach ($input as $item) {
        yield $this->doSomethingWith($item);
    }
}

And quite a lot more. I hope that it's clear from this list that PHP is still evolving today, and you can be sure there's more good stuff to come.

# PHP's performance

Back in the 5.* days, PHP's performance was… average at best. With 7.0 though, large parts of PHP's core were rewritten from the ground up, resulting in two or three times performance increases. Furthermore, each 7.* release has had a positive impact on performance.

Words don't suffice though. Let's look at benchmarks. Luckily other people have spent lots of time in benchmarking PHP performance. I find that Kinsta has a good updated list.

The latest performance related feature is called preloading, which basically allows you to store compiled parts of your PHP code in memory. You can look at some benchmarks over here.

When PHP 8 arrives, we'll also have a JIT compiler at our disposal, promising interesting performance improvements, and allowing PHP to enter new areas besides web development.

# Frameworks and ecosystem

Moving on to what's done by the community with PHP. Let's be clear: PHP isn't just WordPress anymore, on the contrary.

In general there are two major web application frameworks, and a few smaller ones: Symfony and Laravel. Sure there's also Laminas, Yii, Cake, Code Igniter etc. — but if you want to know what modern PHP development looks like, you're good with one of the first two.

Both frameworks have a large ecosystem of packages and products. Ranging from admin panels and CRMs to standalone packages, CI to profilers, numerous services like web sockets servers, queuing managers, payment integrations; honestly there's too much to list.

These frameworks are meant for actual development; if you're instead in need of pure content management, platforms like WordPress, CraftCMS and Statamic are improving more and more.

One way to measure the current state of PHP's ecosystem is to look at Packagist, the main package repository for PHP. It has seen exponential growth. With ±25 million downloads a day, it's fair to say that the PHP ecosystem isn't the small underdog it used to be.

Take a look at this graph, listing the amount of packages and versions over time. It can also be found on the Packagist website.

Besides application frameworks and CMSs, we've also seen the rise of asynchronous frameworks the past years. These are frameworks and servers, written in PHP or other languages, that allow users to run truly asynchronous PHP code. Some major players are Swoole, Amp and ReactPHP.

Since we've ventured into the async world, stuff like web sockets and applications with lots of IO have become actually relevant in the PHP world.

There has also been talk on the internals mailing list to add libuv to the core. For those unaware of libuv: it's the same library Node.js uses to allow all its asynchronicity. Who knows? PHP 8 might be the version adding it to the core!

# In closing

I hope I was able to show you that PHP has evolved tremendously over the past years, and you're perfectly able to write clean and maintainable code with it.

If you're interested in what PHP code looks like in the wild these days, you can check out the source code of one of my own projects, as well as many open source packages we personally maintain.

So while the language definitely has its drawbacks and 20 years of legacy to carry with it; I can say with confidence that I enjoy working with it.

In my experience, I'm able to create reliable, maintainable and quality software. The clients I work for are happy with the end result, as am I. While it's still possible to do lots of messed up things with PHP, I'd say it's a great choice for web development if used wisely and correctly.

Don't you agree? Let me know why! You can reach me via Twitter or e-mail.