PHP is a scripting language used by a large number of users for web development purposes. The latest stable and updated version of PHP, 8.3, was released on 23.11.2023. There have been many innovations and changes since PHP 3.x, released in 2000. PHP is still among the most popular web development (web design) languages ​​used by a very large audience. In this article, we will examine and analyze the innovations and changes in PHP 8.3 with code examples.

PHP 8.3 Major New Features and Improvements

There are many major innovations and improvements in PHP 8.3 compared to the previous PHP version, PHP 8.2. At the same time, some features have been deprecated. We will now examine the innovations and improvements one by one with code examples.

Typed Class Constants

Declaring type is a very important feature for developers that increases stability and reduces error rates in web development. Type declaration feature for properties in a class was added in PHP 7.4. Although many improvements were made to this feature in later versions, this feature was still not available for constants in the class. With PHP 8.3, it is now possible to declare types for constants in classes.

// Doğru kullanım:
class MyClass {
    // Bildirilen tür ve değer aynı
    const string VERSION = "PHP 8.3"; // değer string
}

// Hatalı kullanım:
class MyClass {
    // Bildirilen tür ile değer farklı
    const int VERSION = "PHP 8.3"; // değer string
}

// Hatalı kullanım:
class MyClass {
    // Bildirilen tür sınıf sabitleri için desteklenmiyor
    const void VERSION = "PHP 8.3"; // değer string
}

Some type declarations are not supported for class constants.

Unsupported type declarations for class constants: void, callable, never

A New Function: json_validate()

When working with data in JSON format (json-encoded data), we need to verify that the incoming data is valid before using the data. We were doing this in versions before PHP 8.3 using the following or similar methods.

// PHP 8.3'ten önceki sürümlerde JSON verisini doğrulama

$data = $json_decode($maybeJSON);

if (json_last_error() === JSON_ERROR_NONE) {
    // $data ile gerçekleştirilecek işlemler
}

In this old example, when validating JSON data, PHP can consume significant memory, depending on the size of the data. In PHP 8.3, a new PHP function was added that creates a performance-oriented fast solution: json_validate(). We have exemplified the usage scenario of this function below.

// PHP 8.3'te JSON verisini doğrulama
$data = $json_decode($maybeJSON);

if (json_validate($maybeJSON)) {
    // $data ile gerçekleştirilecek işlemler
}

A New Feature: #[Override]

When implementing interfaces in PHP, we provide detailed functionality for the methods in the interface. When creating an instance of a class, we can override a parent method by creating an alternative version with the same name and compatible signature. This may cause major problems in the software. In short, the problem is that we think we have overridden the main method as a result of a small overlooked typo.

PHP 8.3 #[Override] feature provides a solution for this problem. Now let's see this in the example.

class A {
    protected function myOverrideFunc(): void {}

// Doğru kullanım
// Bu örnek çalışacak
// Üstteki sınıfta ilgili method var ve geçersiz kılındı
class B extends A {
    #[\Override]
    public function myOverrideFunc(): void {}

// Hatalı kullanım
// Bu örnek çalışmayacak, çünkü ana sınıfta method yok
// Muhtemelen gözden kaçan bir yazım hatası
class C extends A {
    #[\Override]
    public function myOverrideFunction(): void {}
}

Deep Cloning of readonly Properties

PHP introduced the possibility of declaring individual class properties as readonly in PHP 8.1 and assigning them to the entire class in PHP 8.2. However, most web developers thought that the limitations imposed when working with classes containing such features prevented practicality in programming logic.

To change this RFC Two main recommendations were made:

readonly

  1. readonly allowing classes that are not allowed to be extended
  2. readonly allowing features to be restarted during cloning

The second suggestion was included in PHP 8.3. This new approach added to PHP 8.3 readonly instances of a class with propertiesreadonly properties) __clone It allows it to be restarted with its magic method.

This code example from the RFC can help us understand how this new method works:

Dynamic Fetching of Class Constants and Enum Members

Unlike other features in PHP, capturing class constants and enum members with variable names is a bit more complicated. Before PHP 8.3 we could do this like the example below:

class Foo {
    public function __construct(
        public readonly DateTime $bar,
        public readonly DateTime $baz
    ) {}

    public function __clone() {
        // Klon çağrıldığında $bar yeni bir DateTime alacak
        $this->bar = clone $this->bar;

        // Ardından bu metod çağrılacak
        $this->cloneBaz();
    }

    private function cloneBaz() {
       // Bu __clone içinden çağrıldığından dolayı doğru bir kullanımdır
        unset($this->baz);
    }
}

$foo = new Foo(new DateTime(), new DateTime());
$foo2 = clone $foo;
class MyClass {
    public const THE_CONST = 9;
}

enum MyEnum: int {
    case FirstMember = 9;
    case SecondMember = 10;
}

$constantName = 'THE_CONST';
$memberName = 'FirstMember';

echo constant('MyClass::' . $constantName);
echo constant('MyEnum::' . #memberName)->value;

Now, let's get the values using the class and enum definitions in the example above in PHP 8.3:

$constantName = 'THE_CONST';
$memberName = 'FirstNumber';

echo MyClass::{$constantName};
echo MyEnum::{$memberName}->value;

A New Method: getBytesFromString()

We can say that this method was the most unexpected among the features added in PHP 8.3: Generating random text using a pre-approved collection of characters.

This new method is very simple and clear. We give some characters to the method as resources and specify how many of them we want to use. That's all! Now our method will return results with random characters until it reaches the specified length. Now let's clarify this with an example

$generateRandomString = new Random\Randomizer();
$allowedChars = 'ABCDEFGHJKMNPQRSTVWXYZ';

$generateRandomString->getBytesFromString($allowedChars, 6) // "MBDSFD" - rastgele gelen veri
$generateRandomString->getBytesFromString($allowedChars, 6) // "DJSDKA" - rastgele gelen veri
$generateRandomString->getBytesFromString($allowedChars, 4) // "SDLA" - rastgele gelen veri

It is possible for the output to be longer than the total length of the characters we specified. We did this in the example below:

$generateRandomString = new Random\Randomizer();
$allowedChars = '123456';

$generateRandomString->getBytesFromString($allowedChars, 8) // "47384252" - rastgele gelen veri

If all the characters we give as parameters are different, the probability of which one will be selected is equal. However, we can make more of the same character appear in the output by adding more than one of the same character to our supported character list. We showed this in the next example.

$generateRandomString = new Random\Randomizer();
$allowedChars = 'AAAAA12345';

$generateRandomString->getBytesFromString($allowedChars, 5) // "4AA12" - rastgele gelen veri
$generateRandomString->getBytesFromString($allowedChars, 8) // "38A19AA5" - rastgele gelen veri

New Methods: getFloat() and nextFloat()

In this innovation, PHP 8.3 introduces two new methods that extend PHP's random extension: getFloat() and nextFloat().

An example of these methods:

$generateRandomNumber = new Random\Randomizer();

// Rastgele ondalıklı (float) bir rakam oluştur
// Değer 0 ile 5 arasında olsun
$generateRandomNumber->getFloat(0,5); // 2.483929 - rastgele gelen veri

// 0 ile 1 arasında rastgele ondalıklı bir rakam oluştur
$generateRandomNumber->nextFloat(); // 0.4828258 rastgele gelen veri

Minor Innovations and Improvements in PHP 8.3

In addition to the above innovations, PHP 8.3 has dozens of other small-scale improvements and innovations. We have listed them together with their source documents in the list below.

Deprecated in PHP 8.3

With every new version of PHP, some code is marked for deprecation. It is never recommended to use these features once they are completely deprecated. If deprecated code is used, an error message will be returned when the code is executed.

List of deprecations in PHP 8.3:

PHP 8.3

In this article, we reviewed the important changes and innovations in PHP 8.3. For a more detailed list of all changes in PHP 8.3 official changelog We recommend you review it. If you want to upgrade your codes or site from PHP 8.2 to PHP 8.3, this guide may be useful: PHP 8.3 Migration Guide -> https://www.php.net/manual/en/migration83.php

If you are worried about PHP versions and migration, we recommend giving the new version some time to upgrade to PHP 8.3.

Full coverage of PHP and JavaScript languages and related technologies as Onur Özden Web Çözümleri Web Software We offer services.  If you have a question or request, you can quickly contact us via the Whatsapp button at the bottom left to get a quote.