Top 20 PHP 8.3 Exciting Features You Can’t Afford to Miss

Learn about the latest enhancements and improvements in PHP 8.3 that revolutionise web development and programming.

Tara Prasad Routray
Level Up Coding

--

Before you start, Introducing you - Tara Dark

A sleek and professional new VS Code theme designed to improve your coding experience. With its dark background and vibrant color accents, Tara Dark provides a visually appealing and comfortable environment for extended coding sessions. Say goodbye to eye strain and hello to maximum productivity.

Download Tara Dark now and take your coding game to the next level.

https://marketplace.visualstudio.com/items?itemName=TaraPrasadRoutray.tara-dark

PHP 8.3, the latest iteration of the popular server-side scripting language, brings a lot of new features and improvements that promise to streamline web development and enhance performance. With enhancements such as readonly classes, the new json_validate() function, additions to the Randomizer class, and more appropriate Date/Time Exceptions, PHP 8.3 is set to revolutionize the PHP development experience. These updates aim to make PHP more efficient, secure, and versatile, catering to the evolving needs of web developers and businesses.

Top 20 Exciting Features & Enhancements of PHP 8.3

  1. Readonly classes improvements
  2. New json_validate() function
  3. Additions to the Randomizer class
  4. Typed class constants
  5. Anonymous readonly classes
  6. Dynamic class constant fetch
  7. More appropriate Date/Time Exceptions
  8. Improved unserialize() error handling
  9. Traits and static properties
  10. Stack overflow detection
  11. Invariant constant visibility
  12. Assert String Eval Cleanup
  13. Improved FFI\CData:void
  14. posix_getrlimit() parameter enhancement
  15. gc_status() improvements
  16. class_alias() support for internal classes
  17. mysqli_poll() error handling
  18. array_pad() enhancements
  19. Removal of opcache.consistency_checks ini directive
  20. Proper handling of the decimal places using the number_format()

1. Readonly class improvements

In PHP 8.3, significant improvements have been made to readonly classes, offering developers more flexibility and control over their code. One notable change is the ability to reinitialize readonly properties while cloning, addressing a specific yet crucial edge case. This enhancement allows for deep cloning of readonly properties, thereby expanding the utility of readonly classes in PHP. Consider the following readonly class with a DateTime property:

readonly class Post {
public function __construct(public DateTime $createdAt) {
// Constructor logic
}

public function __clone() {
$this->createdAt = new DateTime();
// Reinitializing the readonly property is now allowed
}
}

In this example, the Post class has a readonly property $createdAt, which represents the creation date of a post. With the improvements in PHP 8.3, the __clone() method can reinitialize the readonly property, enabling deep cloning of objects without compromising the integrity of readonly properties.

2. New json_validate() function

The introduction of the json_validate() function provides developers with a more efficient and direct approach to validating JSON strings. This function is particularly beneficial when there is a need to determine the validity of a JSON string without the overhead of decoding it.

$jsonString = '{"name": "John", "age": 30, "city": "New York"}';

if (json_validate($jsonString)) {
echo "The JSON string is valid.";
} else {
echo "The JSON string is invalid.";
}

In this example, the json_validate() function is used to validate the JSON string $jsonString directly. If the JSON string is valid, the corresponding message is displayed. This function provides a straightforward way to validate JSON data without the need for decoding and error handling.

You can even specify custom depths and flags.

$jsonString = '{"name": "John", "age": 30, "city": "New York"}';

// Validate JSON string with custom depth and flags
if (json_validate($jsonString, 512, JSON_THROW_ON_ERROR)) {
echo "The JSON string is valid.";
} else {
echo "The JSON string is invalid.";
}

In this example, the json_validate() function is used with custom depth and flags. The second parameter specifies the maximum depth of the JSON string, while the third parameter sets the flags for validation. This allows developers to tailor the validation process based on specific requirements.

The json_validate() function in PHP 8.3 streamlines the JSON validation process, offering a more memory-efficient alternative to decoding JSON strings for validation purposes. This enhancement is particularly valuable in scenarios where only the validity of the JSON data needs to be determined, contributing to improved performance and resource utilization in PHP applications.

3. Additions to the Randomizer class

The Randomizer class has been enhanced with new methods that enable developers to generate random data with greater control and flexibility. These additions expand the capabilities of the Randomizer class, offering improved support for generating random values within specified ranges and constraints.

use Randomizer;

$string = "Hello, World!";
$length = 10;

$randomBytes = Randomizer::getBytesFromString($string, $length);
var_dump($randomBytes);

In this example, the getBytesFromString() method of the Randomizer class is used to generate a string of random bytes with a specified length ($length) from the given input string ($string). This method provides a convenient way to create random byte sequences based on a source string, catering to scenarios where random data generation is required.

You can even generate random integers within a range.

use Randomizer;
use IntervalBoundary;

$min = 10;
$max = 20;

$randomInteger = Randomizer::getRandomInteger($min, $max, IntervalBoundary::Closed);
echo $randomInteger;

In this example, the getRandomInteger() method of the Randomizer class is utilized to generate a random integer within the specified range defined by $min and $max. The IntervalBoundary::Closed enum is used to indicate that the minimum and maximum values should be included in the range. This method empowers developers to produce random integers within specific boundaries, offering precise control over the generated values.

The additions to the Randomizer class in PHP 8.3 equip developers with enhanced capabilities for generating random data, catering to diverse use cases that require controlled randomness. These methods contribute to the overall versatility and utility of the Randomizer class, enriching the spectrum of random data generation options available to PHP developers.

4. Typed class constants

The introduction of typed class constants allows developers to define class constants with specific data types, providing improved type safety and clarity within class definitions. This enhancement enables developers to enforce type constraints on class constants, enhancing code readability and reducing the likelihood of unintended data type mismatches. Let’s explore this feature with a couple of examples:

class MathOperations {
public const PI: float = 3.14159;
public const MAX_ITERATIONS: int = 1000;
}

In this example, the MathOperations class defines two class constants, PI and MAX_ITERATIONS, with specific data types. The PI constant is typed as a float, while the MAX_ITERATIONS constant is typed as an INT. This ensures that these constants hold values of the specified data types, promoting type safety and enhancing code clarity.

class Configuration {
public const DEFAULT_TIMEOUT: int = 30;
public const ENABLE_LOGGING: bool = true;

public function setRequestTimeout(int $timeout): void {
// Set the request timeout using the DEFAULT_TIMEOUT constant
// defined as an integer
// ...
}

public function enableLogging(bool $enable): void {
// Enable or disable logging based on the ENABLE_LOGGING constant
// defined as a boolean
// ...
}
}

In this example, the Configuration class utilizes typed class constants to define default timeout and logging configuration options. The DEFAULT_TIMEOUT constant is typed as an INT, ensuring that it holds integer values, while the ENABLE_LOGGING constant is typed as a boolean, indicating that it holds boolean values. This promotes consistency and type safety when using these constants within the class methods.

The introduction of typed class constants in PHP 8.3 enhances the expressiveness and reliability of class definitions by allowing developers to specify data types for class constants. This feature contributes to improved code quality, better documentation, and reduced potential for data type errors within class constants, ultimately enhancing the robustness of PHP applications.

5. Anonymous readonly classes

The introduction of anonymous readonly classes brings a new level of flexibility to object-oriented programming. These classes allow for the creation of lightweight, immutable objects without the need for explicitly defining a named class. This feature is particularly useful for scenarios where a temporary or one-off object is needed without the overhead of a formal class declaration. Let’s explore this feature with a couple of examples:

$person = new class {
public function __construct(public string $name, public int $age) {}
};

$john = new $person('John Doe', 30);
echo $john->name; // Output: John Doe
echo $john->age; // Output: 30

In this example, an anonymous readonly class is created using the new class { … } syntax. The class has public properties for name and age, and an object $john is instantiated from this anonymous class. This allows for the creation of a simple, lightweight object without the need for a formal class declaration.

You can even use an anonymous readonly class for data structures.

$data = new class {
public array $values = [];

public function addValue($value): void {
$this->values[] = $value;
}
};

$data->addValue('A');
$data->addValue('B');
$data->addValue('C');

print_r($data->values); // Output: Array ( [0] => A [1] => B [2] => C )

In this example, an anonymous readonly class is used to create a simple data structure for storing values. The class has a public property values that holds an array, and a method addValue for adding values to the array. This demonstrates the use of anonymous readonly classes for creating ad-hoc data structures without the need for a formal class definition.

The introduction of anonymous readonly classes in PHP 8.3 provides developers with a lightweight and flexible way to create immutable objects and data structures on-the-fly. This feature enhances the expressiveness and versatility of PHP’s object-oriented capabilities, offering a convenient alternative to traditional class declarations for certain use cases.

6. Dynamic class constant fetch

This feature allows developers to fetch class constants using a more dynamic syntax, providing greater flexibility and expressiveness when working with class constants. Let’s explore this feature with a couple of examples:

class Configuration {
public const DEFAULT_TIMEOUT = 30;
public const ENABLE_LOGGING = true;
}

$constantName = 'DEFAULT_TIMEOUT';
echo Configuration::{$constantName}; // Output: 30

In this example, the value of the DEFAULT_TIMEOUT class constant is fetched dynamically using the variable $constantName. This dynamic syntax allows for the retrieval of class constants based on runtime values, providing a more flexible approach to working with class constants.

You can even use dynamic class constants inside a function.

class Configuration {
public const DEFAULT_TIMEOUT = 30;
public const ENABLE_LOGGING = true;
}

function getConstantValue(string $constantName): mixed {
return Configuration::{$constantName};
}

echo getConstantValue('ENABLE_LOGGING'); // Output: 1 (true)

In this example, a function getConstantValue is defined to dynamically fetch the value of a class constant based on the provided constant name. This demonstrates how the dynamic class constant fetch feature can be utilized within functions to retrieve class constant values dynamically.

The “Dynamic class constant fetch” feature in PHP 8.3 empowers developers with a more dynamic and versatile way to access class constants, allowing for runtime-based retrieval of constant values. This enhancement enhances the expressiveness and flexibility of working with class constants, catering to scenarios where dynamic constant access is beneficial for application logic and functionality.

7. More appropriate Date/Time Exceptions

This feature introduces dedicated exceptions for various date and time-related edge cases, providing more granular and specific error handling in date and time operations. This enhancement aims to improve the robustness and reliability of date and time-related code by offering more precise exception types for different error scenarios. Let’s explore this feature with a couple of examples:

try {
// Date operation that results in a range error
// ...
} catch (DateRangeError $e) {
// Handle specific DateRangeError exception
// Log the error, notify the user, or take appropriate action
// ...
} catch (Exception $e) {
// Fallback to generic exception handling
// ...
}

In this example, a specific DateRangeError exception is caught to handle scenarios where a date operation results in a range error. This allows for targeted error handling specific to date range errors, ensuring that appropriate actions can be taken based on the specific exception type.

You can even handle the date malformed interval string exception.

try {
// Date interval parsing operation
// ...
} catch (DateMalformedIntervalStringException $e) {
// Handle specific DateMalformedIntervalStringException
// ...
} catch (Exception $e) {
// Fallback to generic exception handling
// ...
}

In this example, the DateMalformedIntervalStringException is caught to handle cases where a date interval string is malformed. By using this specific exception type, developers can implement tailored error handling for scenarios involving malformed date interval strings.

The “More appropriate Date/Time Exceptions” feature in PHP 8.3 provides developers with a more precise and structured approach to handling date and time-related errors. By introducing dedicated exceptions for specific date and time edge cases, this enhancement promotes better error management and facilitates more targeted handling of date and time-related exceptions, ultimately contributing to the overall reliability and robustness of date and time operations in PHP applications.

8. Improved unserialize() error handling

This feature enhances the error-handling mechanism for the unserialize() function, providing more consistent and predictable behaviour when encountering issues during the unserialization of data. This improvement aims to streamline error reporting and ensure that unserialize() errors are handled more effectively, leading to better error management and debugging capabilities. Let’s explore this feature with a couple of examples:

$data = '...'; // Serialized data
$result = unserialize($data);
if ($result === false) {
$error = error_get_last();
if ($error && $error['type'] === E_WARNING) {
// Handle unserialize() error as E_WARNING
// Log the error, notify the user, or take appropriate action
// ...
} else {
// Fallback to generic error handling
// ...
}
}

In this example, after attempting to unserialize the data, the code checks if the result is false, indicating an error. It then retrieves the last error using error_get_last() and examines the error type. If the error type is E_WARNING, it handles the unserialize() error as a warning, allowing for specific error handling tailored to unserialize() issues.

You can even use exception handling with the unserialize method.

$data = '...'; // Serialized data
try {
$result = unserialize($data);
// Process unserialized data
// ...
} catch (UnserializeException $e) {
// Handle specific UnserializeException
// Log the error, notify the user, or take appropriate action
// ...
} catch (Exception $e) {
// Fallback to generic exception handling
// ...
}

In this example, the code utilizes a try-catch block to handle the unserialization process. If an UnserializeException is thrown, it allows for specific error handling dedicated to unserialize() exceptions, enabling developers to implement targeted error management for unserialize() issues.

The “Improved unserialize() error handling” feature in PHP 8.3 introduces more consistent and structured error handling for the unserialize() function, offering developers enhanced control over error reporting and management during the unserialization of data. By providing more predictable error handling mechanisms, this improvement contributes to improved debugging capabilities and overall error resilience when working with serialized data in PHP applications.

9. Traits and static properties

This feature introduces a behaviour change related to the usage of traits with static properties. This enhancement addresses the redeclaration of static properties inherited from a parent class when used in traits, ensuring that each class incorporating the trait maintains a separate storage for the static properties. This behaviour is now analogous to adding the static property directly to the class without traits, promoting a more predictable and consistent handling of static properties within traits. Let’s explore this feature with a couple of examples:

trait Loggable {
protected static $log = [];

public static function addToLog($message) {
self::$log[] = $message;
}

public static function getLog() {
return self::$log;
}
}

class User {
use Loggable;
}

class Product {
use Loggable;
}

User::addToLog('User logged in');
Product::addToLog('New product added');

var_dump(User::getLog());
var_dump(Product::getLog());

In this example, the Loggable trait contains a static property $log along with methods to add messages to the log and retrieve the log. The User and Product classes both use the Loggable trait to incorporate the logging functionality. Each class maintains its own separate storage for the static property $log, ensuring that the log data is isolated and distinct between the User and Product classes.

You can even use traits with the initialization of static property

trait Counter {
protected static int $count = 0;

public static function increment() {
self::$count++;
}

public static function getCount() {
return self::$count;
}
}

class Order {
use Counter;
}

class Invoice {
use Counter;
}

Order::increment();
Invoice::increment();
Order::increment();

var_dump(Order::getCount()); // Output: int(2)
var_dump(Invoice::getCount()); // Output: int(1)

In this example, the Counter trait initializes a static property $count and provides methods to increment the count and retrieve the count value. The Order and Invoice classes use the Counter trait to track the count of orders and invoices separately. Each class maintains its own count, demonstrating the separate storage of static properties within traits for different classes.

The “Traits and static properties” feature in PHP 8.3 ensures that traits with static properties behave consistently and predictably when used in multiple classes, providing a more robust and intuitive mechanism for working with static properties in trait-based code structures.

10. Stack overflow detection

This feature introduces two new ini directives, namely zend.max_allowed_stack_size and zend.reserved_stack_size, to detect and prevent stack overflow situations. This enhancement aims to improve the reliability and stability of PHP applications by detecting and handling stack overflow conditions, thereby reducing the likelihood of segmentation faults and making debugging easier. Let’s explore this feature with a couple of examples:

// php.ini
zend.max_allowed_stack_size = 128K

In this example, the zend.max_allowed_stack_size directive is set to 128 kilobytes in the php.ini configuration file. This directive specifies the maximum allowed stack size for PHP programs, enabling developers to define an upper limit for the call stack size.

// php.ini
zend.reserved_stack_size = 16K

// PHP code
function recursiveFunction($n) {
if ($n <= 0) {
return;
}
recursiveFunction($n - 1);
}

recursiveFunction(100000); // Recursive call with a large number

In this example, the zend.reserved_stack_size directive is set to 16 kilobytes in the php.ini configuration file. The PHP code contains a recursive function that makes a large number of recursive calls, potentially leading to a stack overflow situation. With the zend.reserved_stack_size directive in place, PHP can detect when the call stack is close to overflowing and handle the situation by throwing an Error, preventing segmentation faults and making debugging easier.

The “Stack overflow detection” feature in PHP 8.3 provides developers with the means to set limits on the call stack size and detect potential stack overflow scenarios, thereby enhancing the stability and robustness of PHP applications. By introducing these ini directives, PHP offers improved error handling for stack overflow situations, reducing the likelihood of segmentation faults and facilitating more effective debugging processes.

11. Invariant constant visibility

This feature introduces the ability to declare class constants with the invariant keyword, ensuring that the visibility of the constant remains invariant when extended by a subclass. This enhancement provides a more explicit and controlled way to define class constants, maintaining their visibility across inheritance hierarchies. Let’s explore this feature with a couple of examples:

class ParentClass {
public invariant int MAX_VALUE = 100;
}

class ChildClass extends ParentClass {
// Attempting to change the visibility of MAX_VALUE will result in a compilation error
protected invariant int MAX_VALUE = 200;
}

In this example, the ParentClass declares a public invariant constant MAX_VALUE with a value of 100. When the ChildClass attempts to change the visibility of MAX_VALUE to protected, a compilation error occurs, enforcing the invariant visibility of the constant across the inheritance hierarchy.

You can also use invariant constants in the interface.

interface Constants {
public invariant string VERSION = '1.0';
}

class ImplementationClass implements Constants {
// The visibility of VERSION must remain public in the implementing class
private invariant string VERSION = '2.0';
}

In this example, the Constants interface declares a public invariant constant VERSION with a value of ‘1.0’. When the ImplementationClass attempts to change the visibility of VERSION to private, a compilation error occurs, ensuring that the visibility of the constant remains invariant as specified by the interface.

The “Invariant constant visibility” feature in PHP 8.3 provides a more robust and explicit way to define class constants, ensuring that their visibility remains consistent and invariant across inheritance hierarchies and interface implementations. This enhancement promotes better code maintainability and reduces the likelihood of unintended changes to constant visibility, contributing to the overall reliability and predictability of PHP codebases.

12. Assert String Eval Cleanup

This feature involves the deprecation of string-evaluated code assertions, promoting safer and more maintainable coding practices. This enhancement aims to discourage the use of string-evaluated code for assertions, which can lead to security vulnerabilities and code maintenance challenges. Let’s explore this feature with a couple of examples:

assert('is_numeric($value)');

In this example, the assert function is used with a string-evaluated code assertion to check if $value is numeric. However, this approach is prone to security risks and is being deprecated in PHP 8.3.

Here is the updated version of assertion using the direct expression.

assert(is_numeric($value));

In PHP 8.3, the recommended approach is to use direct expressions for assertions instead of string-evaluated code. By directly invoking the is_numeric function within the assert statement, the code becomes more secure and easier to maintain.

The “Assert String Eval Cleanup” feature in PHP 8.3 encourages developers to transition away from using string-evaluated code for assertions, promoting safer and more reliable coding practices. By deprecating this approach, PHP aims to enhance code security and maintainability, ultimately contributing to the overall robustness of PHP applications.

13. Improved FFI\CData:void

This feature involves the enhancement of the FFI (Foreign Function Interface) extension to allow C functions with a return type of void to be represented as null in PHP, instead of returning an instance of FFI\CData<void>. This improvement simplifies the handling of C functions that do not return a value, aligning the behavior with the expected null return type in PHP. Let’s explore this feature with a couple of examples:

// C code
void myFunction() {
// Function implementation
}

// PHP FFI
$ffi = FFI::cdef("
void myFunction();
", "mylib.so");

$ffi->myFunction(); // Invoking the C function

In this example, the C function myFunction has a return type of void. In PHP 8.3, when invoking this function using FFI, the return value will be null instead of an instance of FFI\CData<void>, simplifying the handling of void-returning C functions.

You can even check the return type like this:

$result = $ffi->myFunction();

if ($result === null) {
echo "Function executed successfully and returned null.";
} else {
echo "Unexpected return value.";
}

In this example, the return value of the C function myFunction is checked. If the return value is null, it indicates that the function executed successfully and did not return a value, aligning with the expected behavior for void-returning functions.

The “Improved FFI\CData:void” feature in PHP 8.3 streamlines the representation of void-returning C functions in PHP, simplifying the interaction with such functions through FFI. By allowing these functions to be represented as null in PHP, this enhancement contributes to a more intuitive and consistent FFI experience when working with C functions that do not return a value.

14. posix_getrlimit() parameter enhancement

This feature introduces an improvement to the posix_getrlimit() function, allowing it to take an optional parameter to fetch a single resource limit. This enhancement provides greater flexibility and precision when retrieving resource limits for a specific resource, streamlining the process of obtaining detailed resource usage information within PHP applications. Let’s explore this feature with a couple of examples:

// Fetching the soft limit for maximum number of open files
$softLimit = posix_getrlimit(posix_RLIMIT_NOFILE, POSIX_RLIMIT_SOFT);
echo "Soft limit for maximum number of open files: " . $softLimit . "\n";

In this example, the posix_getrlimit() function is used to fetch the soft limit for the maximum number of open files. With the optional parameter POSIX_RLIMIT_SOFT, the function retrieves and returns the specific resource limit, providing detailed information about the resource usage.

You can even fetch the hard limit for CPU time.

// Fetching the hard limit for CPU time
$hardLimit = posix_getrlimit(posix_RLIMIT_CPU, POSIX_RLIMIT_HARD);
echo "Hard limit for CPU time: " . $hardLimit . "\n";

In this example, the posix_getrlimit() function is utilized to obtain the hard limit for CPU time. By specifying POSIX_RLIMIT_HARD as the optional parameter, the function retrieves and returns the specific resource limit, enabling precise access to resource usage details.

The “posix_getrlimit() parameter enhancement” in PHP 8.3 empowers developers with the ability to fetch individual resource limits, offering a more granular and targeted approach to retrieving resource usage information. This enhancement enhances the precision and flexibility of working with resource limits, catering to scenarios where detailed resource limit information is essential for effective resource management within PHP applications.

15. gc_status() improvements

The gc_status() function has been enhanced to provide a more comprehensive view of the garbage collection process by introducing eight new fields. These fields offer detailed information about various aspects of memory management and garbage collection within PHP applications.
The new fields include:

  • “running” => bool: Indicates whether garbage collection is currently running.
  • “protected” => bool: Indicates whether memory blocks are protected from garbage collection.
  • “full” => bool: Indicates whether a full garbage collection cycle is in progress.
  • “buffer_size” => int: Specifies the buffer size for garbage collection, measured in bytes.
  • “application_time” => float: Represents the total application time, including the time spent on garbage collection cycles.
  • “collector_time” => float: Reflects the time spent on collecting cycles, encompassing the execution of destructors and freeing of values.
  • “destructor_time” => float: Indicates the time spent executing destructors during cycle collection.
  • “free_time” => float: Represents the time spent freeing values during cycle collection.
$status = gc_status();
echo "Garbage collection running: " . ($status['running'] ? 'Yes' : 'No') . "\n";
echo "Protected memory blocks: " . ($status['protected'] ? 'Yes' : 'No') . "\n";
echo "Full garbage collection in progress: " . ($status['full'] ? 'Yes' : 'No') . "\n";
echo "Buffer size for garbage collection: " . $status['buffer_size'] . " bytes\n";
echo "Total application time: " . $status['application_time'] . " seconds\n";
echo "Time spent collecting cycles: " . $status['collector_time'] . " seconds\n";
echo "Time spent executing destructors: " . $status['destructor_time'] . " seconds\n";
echo "Time spent freeing values: " . $status['free_time'] . " seconds\n";

By accessing these fields, developers can gain valuable insights into the status of garbage collection, memory protection, cycle collection times, and resource utilization. This detailed information empowers developers to make informed decisions regarding memory.

16. class_alias() support for internal classes

This feature extends the functionality of the class_alias() function to support the creation of aliases for internal PHP classes. This enhancement provides greater flexibility and convenience when working with internal classes, allowing developers to create alternative names for existing internal classes, thereby simplifying class references and promoting code readability. Let’s explore this feature with a couple of examples:

class_alias('DateTime', 'MyDateTime');

In this example, the class_alias() function is used to create an alias MyDateTime for the internal PHP class DateTime. This allows developers to refer to the DateTime class using the alias MyDateTime throughout the codebase, providing a more descriptive or contextual name for the class.

You can even use the class alias for internal class initialization.

$date = new MyDateTime('2023-11-24');
echo $date->format('Y-m-d');

In this example, the alias MyDateTime is utilized to instantiate an object of the internal class DateTime. The alias provides a more intuitive and meaningful name for the class instantiation, enhancing code clarity and maintainability.

The “class_alias() support for internal classes” feature in PHP 8.3 streamlines the process of creating aliases for internal classes, offering developers a convenient mechanism to define alternative names for internal classes, thereby improving code organization and readability. This enhancement contributes to a more expressive and coherent codebase, allowing for clearer and more contextually relevant class references within PHP applications.

17. mysqli_poll() error handling

This feature introduces a behavior change related to error handling. Specifically, when the mysqli_poll() function is called without providing the read nor error arguments, it now raises a ValueError. This enhancement ensures that the mysqli_poll() function is used with the appropriate arguments, promoting more robust and predictable error handling in scenarios involving asynchronous MySQL query execution. Let’s consider an example to illustrate this behavior:

$links = [...]; // Array of MySQL links
$read = $error = $reject = [];
if (mysqli_poll($links, $read, $error, $reject, $timeout)) {
// Process the results
foreach ($read as $link) {
// Handle successful query execution
}
foreach ($error as $link) {
// Handle query execution errors
}
foreach ($reject as $link) {
// Handle rejected connections
}
} else {
// Handle polling errors
}

In this example, the mysqli_poll() function is called with the correct arguments, including the $read, $error, and $reject arrays. This usage adheres to the updated behavior in PHP 8.3, ensuring that the function is invoked with the necessary arguments to handle the results of the polling operation.

By raising a ValueError when the read nor error arguments are not passed, PHP 8.3 promotes more explicit and reliable error handling practices, encouraging developers to provide all required arguments for mysqli_poll() calls. This enhancement contributes to the overall robustness and predictability of asynchronous MySQL query execution in PHP applications.

18. array_pad() enhancements

This feature removes the previous limitation on the number of elements that can be added at a time using the array_pad() function. Prior to this enhancement, it was only possible to add at most 1048576 elements at a time when padding an array.

However, with the improvements introduced in PHP 8.3, the array_pad() function is now only limited by the maximum number of elements an array can have, providing developers with greater flexibility and eliminating the previous constraint on the number of elements that can be added through array padding operations.

This enhancement allows developers to pad arrays with a significantly larger number of elements, enabling them to work with arrays of varying sizes without being restricted by the previous limitation. As a result, developers can leverage the array_pad() function more effectively in scenarios that require extensive array manipulation and dynamic resizing, contributing to enhanced flexibility and scalability in array padding operations within PHP applications.

19. Removal of opcache.consistency_checks ini directive

This feature signifies the removal of the opcache.consistency_checks ini directive, which was previously used to enable or disable consistency checks in OPCache. This removal simplifies the OPCache configuration by eliminating the need for managing the opcache.consistency_checks directive, streamlining the OPCache setup and maintenance process. Here’s an example of how this change impacts OPCache configuration:

Previous OPCache Configuration with opcache.consistency_checks.

opcache.consistency_checks=1

In this example, the opcache.consistency_checks directive is set to 1 to enable consistency checks in OPCache.

With the removal of the opcache.consistency_checks directive in PHP 8.3, the configuration for consistency checks in OPCache is no longer necessary, simplifying the OPCache configuration process.

This change reflects a streamlined approach to OPCache configuration, reducing the complexity of managing OPCache consistency checks and aligning with the goal of enhancing the overall efficiency and usability of OPCache in PHP 8.3.

20. Proper handling of the decimal places using the number_format()

This function has been enhanced to properly handle negative integers for the $decimal parameter. Rounding with a negative value for $decimal now means that $num is rounded to the specified number of significant digits before the decimal point. Previously, negative $decimals were silently ignored, and the number got rounded to zero decimal places. Let’s explore this feature with a couple of examples:

$num = 1234.56789;
$formatted1 = number_format($num, 2); // 1,234.57
$formatted2 = number_format($num, -2); // 1,200

In this example, the number_format() function properly handles the negative $decimal value, rounding the number to the specified number of significant digits before the decimal point.

This enhancement ensures more consistent and predictable behavior when rounding numbers using the number_format() function, providing developers with greater control over the formatting of numeric values.

Kudos! You have completed learning about the top 20 features and improvements introduced in PHP 8.3. This latest release brings a wealth of enhancements that cater to the evolving needs of developers and businesses, empowering them to write more efficient, reliable, and maintainable code.

If you enjoyed reading this article and have found it useful, then please give it a clap, share it with your friends, and follow me to get more updates on my upcoming articles. You can connect with me on LinkedIn. Or, you can visit my official website: tararoutray.com to know more about me.

--

--