What's New in PHP 8.3: Discover the Exciting Features and Enhancements

As the PHP project adheres to its annual tradition of releasing a new major or minor version towards the end of each year, PHP 8.3 is no exception.

This latest iteration brings forth many new features and enhancements, further solidifying PHP's standing as a versatile and evolving language.

In this article, we will delve into the noteworthy additions and changes introduced in PHP 8.3, shedding light on the key aspects developers need to be aware of.

PHP 8.3: New and Exciting Features

1. Typed Class Constants

In PHP 8.3, a noteworthy improvement comes in the form of typed class constants. This new feature allows developers to specify types for class constants, promoting type coherence and minimizing the chances of inadvertent deviations from the original declaration. This enhancement applies not only to class constants but also extends to constants within interfaces, traits, and enums.

The introduction of typed class constants is particularly beneficial for preserving type uniformity when dealing with subclasses derived from base declarations. This helps prevent unintentional modifications to the type, thereby reducing the risk of compatibility issues.

interface ConstTest {
    const string VERSION = "PHP 8.3";
}

// Illegal:
interface ConstTest {
    const float VERSION = "PHP 8.3";
}

2. stream_context_set_options Function

The release of PHP 8.3 introduces an enhanced function called stream_context_set_options, which improves upon the existing stream_context_set_option. This new function is designed to handle multiple options and is anticipated to supplant the original function in upcoming PHP versions.

php

stream_context_set_options($stream_or_context, ['http' => ['method' => 'POST']]);

This update enhances stream context manipulation by providing a more versatile and future-proof API.

3. Randomizer::getBytesFromString Method

In PHP 8.3, the \Random\Randomizer class introduces the getBytesFromString method, which facilitates the creation of random sequences derived from a designated character string. This functionality is particularly valuable for generating secure random bytes from a predetermined set of characters. The inclusion of this method enhances the versatility of random data generation, empowering developers to define the origin of characters for the selection of random bytes.

php

$rng = new Random\Randomizer();
$alpha = 'ABCDEFGHJKMNPQRSTVWXYZ';

$rng->getBytesFromString($alpha, 6); // "MBXGWL"
$rng->getBytesFromString($alpha, 6); // "LESPMG"
$rng->getBytesFromString($alpha, 6); // "NVHWXC"

4. Fallback Value Support for PHP INI Environment Variable Syntax

With the introduction of version 8.3, PHP developers now can define default values for PHP INI settings in cases where specific environment variables are not present. This enhancement enhances configurability by offering default values, streamlining configuration management, and facilitating the smooth handling of absent environment variables.

php

// Fallback to 'Foo' if SESSION_NAME is not set
session.name = ${SESSION_NAME:-Foo}

// Fallback to '' if MAIL_FROM_USER or MAIL_FROM_DOMAIN is not set
sendmail_from = "${MAIL_FROM_USER:-info}@${MAIL_FROM_DOMAIN:-example.com}"

5. class_alias() Supports Aliasing Built-in PHP Classes

With the introduction of PHP 8.3, the class_alias() function now supports the aliasing of built-in PHP classes. This enhancement empowers developers to utilize class_alias() for establishing alternative names for fundamental PHP classes, offering increased versatility in code structuring and naming conventions. Consequently, this improvement facilitates the creation of more organized and expressive code when dealing with native PHP classes.

6. Dynamic Class Constant and Enum Number Fetch Support

PHP 8.3 introduces a simplified approach to retrieve class constants and enum members using variable names. The previously cumbersome constant() function usage is replaced with a more intuitive syntax, which enhances the readability of code. This enhancement streamlines the dynamic access of class constants and enum members.

php

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

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

7. Randomizer::getFloat() and nextFloat() Methods

Building upon the enhancements made in the Random extension, PHP 8.3 introduces two additional techniques for producing random float values: getFloat() and nextFloat(). These methods offer improved precision and increased control over the generation of random floating-point numbers, empowering developers with greater flexibility in obtaining random float values within defined ranges.

php

$rng = new Random\Randomizer();

// Generate a float value between 0 and 5
$rng->getFloat(0, 5); // 2.3937446906217

8. json_validate() Function

Before PHP 8.3, checking the syntactic correctness of a JSON-encoded string required using json_decode() and examining for errors. The introduction of the json_validate() function streamlines this procedure, as it validates the JSON syntax without necessitating the creation of associative arrays or objects, thus preserving memory. This function proves especially beneficial for validating JSON payloads before they are stored or delivered in a request-response context.

php

if (json_validate($maybeJSON)) {
    // Do something with $maybeJSON  
}

9. gc_status() Now Returns Additional Information

In PHP 8.3, the gc_status() function, which is tasked with delivering statistics related to the garbage collector, undergoes an improvement. The upgraded function now furnishes extra details, encompassing information about the ongoing status, protection status, buffer size, and other relevant parameters. This enhancement offers developers a more extensive and insightful perspective on the garbage collector's behavior.

php

$gcStatus = gc_status();
echo "Running: " . $gcStatus['Running'];
echo "Memory usage before collection: ".$gcStatus['memoryUsageBefore'];
echo "Memory usage after collection: " .$gcStatus['memoryUsageAfter'];

10. PHP CLI Lint Supports Linting Multiple Files at Once

PHP 8.3 introduces a noteworthy enhancement that enables the simultaneous linting of multiple files within a single PHP CLI linting process invocation. This improvement streamlines the syntax error-checking workflow, enhancing efficiency when examining multiple files. This update contributes to a more streamlined developer experience by allowing the concurrent linting of multiple files.

bash

php -l file1.php file2.php file3.php

Deprecations and Changes in PHP 8.3

1. unserialize(): E-NOTICE to E-WARNING

In PHP 8.3, there is a modification in the behavior of the unserialize() function. Specifically, error conditions that used to trigger notices (E_NOTICE) will now generate warnings (E_WARNING). This adjustment encompasses scenarios like syntax errors and issues with custom __unserialize handlers.

2. get_class() and get_parent_class() Changes

In PHP 8.3, the practice of invoking get_class() and get_parent_class() without parameters has been deprecated. This modification is intended to enhance the efficiency of these functions and remove any potential ambiguities resulting from multiple function signatures.

php

class MyException extends InvalidArgumentException {
    public function __construct() {
        get_class();             // Deprecated in PHP 8.3
        get_parent_class();      // Deprecated in PHP 8.3
    }
}

Developers are advised to include the $object parameter when utilizing these functions to prevent deprecation notices.

php

// PHP 8.3
unserialize('invalid_data'); // Now emits E_WARNING for syntax errors

This change promotes consistency in error handling and encourages developers to handle unserialized errors more proactively.

3. HTML Highlight Tag Changes

In PHP 8.3, notable modifications have been introduced to the syntax highlighting functions, specifically highlight_file and highlight_string. The HTML output generated by these functions is now enclosed within <pre><code></code></pre> tags. Notably, line breaks are no longer transformed into <br/> tags, and both white spaces and tabs are no longer converted into HTML entities. This refinement enhances the legibility of the highlighted code and adheres more closely to contemporary HTML standards.

php

$code = file_get_contents('example.php');
echo highlight_string($code, true);

4. Granular DateTime Exceptions

In PHP 8.3, there is an introduction of specialized Exception and Error classes tailored for date-related issues. This enhancement offers a higher level of detail when errors occur, specifically in the context of date and time operations. These extension-specific classes contribute to a more precise error reporting system, empowering developers to better identify and resolve date-related errors with increased efficiency.

php

try {
    // DateTime-related operation
} catch (\DateTimeException $e) {
    // Handle DateTime-specific exception
} catch (\Exception $e) {
    // Handle other exceptions
}

Conclusion

Although PHP 8.3 doesn't bring groundbreaking features like its predecessors, such as PHP 8.0 and 8.1, its focus is on refining the language, aligning features with evolving industry standards, and addressing syntax and error handling aspects. Developers and teams familiar with these enhancements can strategically leverage them to enhance code quality and maintainability.

For those contemplating a shift to PHP 8.3, it is advisable to thoroughly review the documentation to ensure a seamless adaptation to the new features and changes.

In the realm of top backend frameworks in the 2024 landscape, PHP, accompanied by its dynamic Laravel framework, emerges as a standout. Widely acclaimed for its power and flexibility, PHP with Laravel is generating buzz among developers everywhere. The combination opens up endless possibilities for development.