image

PHP 8.3. What cool features now?

On 23.11.2023 the new PHP 8.3 was released on schedule and officially considered a minor release but some changes can directly affect your work with PHP. In this article, I will mention a couple of improvements that I was waiting for or that improved my work.

json_validate()

Honestly, I don't understand why PHP didn't have this method before. In the era of headless applications, access to a lot of information by the API services, and the fact that JSON format was invented in the early 2000s it was a missing piece of the puzzle. In the previous version of PHP, we were forced to use some strange techniques to check if JSON is valid. The most popular that I met was just decoding JSON responses and checking if there were some errors. This was not a cool solution or even elegant code.

Now, finally, we have like the knight on the white horse - the method - json_validate() which returns a bool value depending on whether the JSON response is valid or not

var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true

The command line linter

The command line linter now accepts variadic input for filenames to lint

// Before PHP 8.3
> php -l foo.php bar.php
No syntax errors detected in foo.php

// PHP 8.3
> php -l foo.php bar.php
No syntax errors detected in foo.php
No syntax errors detected in bar.php

Typed class constants

One of the main features of this release is adding the possibility to specify a type of constant variables in classes, interfaces, traits, and enum. It can improve code readability and secure us against future bugs that are hard to detect.

interface I {
    const string PHP = 'PHP 8.3';
}

class Foo implements I {
    const string PHP = [];
}

#[\Override] attribute

This attribute added to the method ensures that a method with the same name exists in the parent class or interface and an override process is intended.

PHP < 8.3

use PHPUnit\Framework\TestCase;

final class MyTest extends TestCase {
    protected $logFile;

    protected function setUp(): void {
       $this->logFile = fopen('/tmp/logfile', 'w');
    }

    protected function taerDown(): void {
       fclose($this->logFile);
        unlink('/tmp/logfile');
    }
}
// The log file will never be removed, because the
// method name was mistyped (taerDown vs tearDown).

PHP 8.3

use PHPUnit\Framework\TestCase;

final class MyTest extends TestCase {
    protected $logFile;

    protected function setUp(): void {
        $this->logFile = fopen('/tmp/logfile', 'w');
    }

    protected function taerDown(): void {
        fclose($this->logFile);
        unlink('/tmp/logfile');
    }
}
// Fatal error: MyTest::taerDown() has #[\Override] attribute,
// but no matching parent method exists

Of course, those are not all improvements. Does release 8.3 add the improvements that you were waiting for?

Leave a Comment