Is PHP Relevant In 2021?

The focus has long since moved from PHP to JavaScript and Python. Nevertheless, new versions are coming out, and the performance tests indicate good progress. How relevant is PHP today? Under the cut – the thoughts of the developer, who continues to give preference to him.

A brief history of PHP

PHP developed Rasmus Lerdorf in 1994. Lerdorf created a set of scripts that tracked visits to his online resume and called them Personal Home Page Tools. Over time, the name evolved into PHP Tools. He replenished this set with new tools, and then decided to rewrite them: he added interaction with databases and much more. So the kit became a framework.

Further, these tools continued to evolve into even more complex primitives, and after the publication of the code in open source in 1995, the number of users began to grow noticeably faster. If you are interested in the details of this story, you can find them at official PHP site

The latest version of the language is PHP 8.0 now.

What’s wrong with PHP?

For many years now, this language has been a target for criticism. People rightly reproach him for his work problems, especially the older versions. Lerdorf developed PHP as a templating language, not a full-featured programming language. Therefore, it has a number of disadvantages that greatly complicate the maintenance and development of large applications.

Weak typing

Personally, I do not like weak typing in this language, which allows you to combine different types and perform their implicit conversions. Consider this example:

echo "1" + 3;
echo 1 + "3";
echo "1" + "3";

The result of these operations will be the number 4, that is, in the context of the addition operator, the language converts the numbers in the string to integer values. In some cases this may be desirable or save a couple of lines of code, but the larger the project becomes, the more difficult it will be to maintain.

In later versions of the language, warnings about such strange and illegal operations began to appear, that is, they are deprecated or will soon become them.

Lack of namespaces

Namespace support was added to PHP in version 5.3. In older projects, you had to create your own namespace types, mostly by adding namespaces to class and method names. Because of this, absurdly long names had to be used throughout.

In projects developed in previous versions, you can often find classes like Payments_Provider_Processor_Provider_SomeExternalServiceProvideralthough it could just be called SomeExternalServiceProvider… In most cases, this results in bloated code and makes it harder to read and parse.

There are no such problems in later versions of the language.

Inconsistent Standard Library Functions

I won’t say that the standard language library is bad, but it could be better. The language has evolved quite a bit, but the first versions of the standard library that are still referenced and maintained for backward compatibility lack consistency. While this is a minor problem, it means that many functions in the standard library have different naming rules, names, and argument order. This all makes it difficult to identify their default values ​​and behavior.

Here are some examples of inconsistent names in string methods from the documentation:

  • strpos(string $haystack, string $needle, int $offset = 0): int|false: finds the position of the first occurrence of a substring in a string;

  • strsplit(string $string, int $length = 1): array : converts a string to an array;

  • explode(string $separator, string $string, int $limit = PHP_INT_MAX): array: splits the line at the boundary line.

Three different functions: one with a prefix str, the second with the prefix str_and the third is without a prefix. Argument $string is the first for str_splitbut second for explode… You can explore all string methods in documentation – this pattern is followed by many functions, that is, there is no particular uniformity among them.

Superglobals

This is more a matter of personal preference – I hate using globals and therefore superglobal… When you find some old homemade projects, you are especially likely to come across the infamous variables like $SERVER or $REQUEST… Don’t get me wrong: they are sometimes very useful and need to be used from time to time. However, to use these values ​​safely, the first step is to encapsulate them in reusable classes. Failure to do so can make interacting with values ​​or making changes to a large project very difficult, as there are many hidden dependencies associated with these values.

And what’s good about PHP?

The language has made a bad impression on many, but it has improved a lot in recent years. Thanks to the release of PHP 7, the language has been modernized, it has many nice features at its base, the speed of work and usability have increased.

Type hints

This is one of my favorite ways to modernize legacy PHP code: using optional type hints to perform type conversions and also provide code documentation. Consider a simple function:

function isValueSomething($value) {}

If you add type hints, the code looks like this:

function isValueSomething(string $value): bool {}

Just by seeing the signature of a function, we know that it expects a string value and will return a boolean result. You might add that it would be useful to use the correct naming here, but these type hints ensure that the values ​​are of the specified types and provide the IDE with auto-completion and static analysis with warnings and other useful things.

Since version 7.4 PHP allows you to set typed properties for classes:

class Person {
    public string $firstName;

    public string $lastName;

    public int $age;

    public ?string $job;
}

This means that objects Person there will be string first and last name, age in integer and nullable string for position. The more classes there are, the more useful this feature is.

Syntax improvements

There are many syntactic improvements in later versions of PHP:

  • arrow functions: fn ($x, $y) => $x + $y;

  • concatenation operator with undefined value: $value = $array['key'] ?? 'default value';

  • assignment with undefined value: return $cache['key'] ??= computeSomeValue('key');

  • expanding arrays: $first = ['a', 'b']; $second = ['c', 'd']; $final= […$first, …$second];

  • named arguments: array_fill(start_index: 0, num: 100, value: 50);

  • numeric literal separator: 299_792_458

In addition to syntax, it contains opportunities for complex improvements.

Constructor promotion

Take a look at the class Person:

class Person {
    private string $firstName;

    private string $lastName; 

    protected int $age;

    public ?string $job;

    public function __construct(
        string $firstName,
        string $lastName,
        int $age,
        ?string $job
    ){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->age = $age;
        $this->job = $job;
    }
}

Instead of this redundant verbose code PHP 8 supports the ability to write code like this:

class Person {
    public function __construct(
        private string $firstName,
        private string $lastName,
        protected int $age,
        public ?string $job
    ){}
}

Convenient, isn’t it?

Nullsafe operator

This operator existed in some other languages ​​like JavaScript, but PHP did not support it. Take a look at the code I took from PHP documentation:

<?
if (is_null($repository)) {
    $result = null;
} else {
    $user = $repository->getUser(5);
    if (is_null($user)) {
        $result = null;
    } else {
        $result = $user->name;
    }
}

This is how the logic was written in older versions of PHP to account for null checks. The new nullsafe operator brings it down to code like this:

$result = $repository?->getUser(5)?->name;

Isn’t it great?

Combined types

Although this is not my favorite thing, it is still valuable in cases where there are already several possible types without type hints. Associations allow you to define multiple value types as variants. Thanks to unions, the following code becomes working:

function doSomething(int|string $value): bool|array {}

Typically, having multiple return types signals an improvement in your code, but previous versions of PHP did not allow you to specify types at all in such cases, so this is still an improvement.

Performance

I do not have clear data to compare performance with other languages, but compared to previous versions, the speed of PHP code has noticeably increased. In addition to the leap that PHP 7 has made over PHP 5.6, all subsequent releases have made improvements, and this trend continues. Conducted by Phoronix Benchmarks show that the latest version of PHP 8 is more than three times faster than PHP 5.6. There are detailed tests in the post at the link above, so they are worth exploring.

In addition to these benchmarks Kinsta also conducted real tests with WordPress. Here is the result for WordPress 5.3.

The exact numbers of measurements are as follows:

  • Benchmark results for WordPress 5.3 with PHP 5.6: 97.71 req / s

  • WordPress 5.3 benchmark results with PHP 7.0: 256.81 req / s

  • WordPress 5.3 with PHP 7.1 benchmark results: 256.99 req / s

  • Benchmark results for WordPress 5.3 with PHP 7.2: 273.07 req / s

  • Benchmark results for WordPress 5.3 with PHP 7.3: 305.59 req / s

  • Benchmark results for WordPress 5.3 with PHP 7.4: 313.42 req / s

PHP 8 is not yet included in these benchmarks, but it is clear that even version 7.4 is capable of handling three times as many requests as compared to 5.6, and this is a major improvement.

Output

In general, PHP has been greatly improved in recent years, and it has become more convenient to work with. I write professionally in Golang, PHP and Python, but most of my experience is in PHP, so I can get biased. However, in my opinion PHP has found the perfect balance between flexibility and maintainability.

It has the tools you need to do crazy things, a flexible type system that allows you to incrementally improve your legacy code, it’s fast enough for most uses, it continues to improve, and it has an amazing open source community.

For those who have become disillusioned with PHP when working with older versions, I recommend giving it another chance. You may not like it anyway, but I believe that many will change their minds by taking an impartial look at the new version.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *