New Features in PHP 8.3: A Comprehensive Guide with Code Examples

Home / Blog / New Features in PHP 8.3: A Comprehensive Guide with Code Examples


`PHP 8.3`, released in late 2023, continues `PHP`’s evolution with a suite of powerful new features, syntax enhancements, and performance improvements. This article explores the standout additions in `PHP 8.3`, complete with practical code examples to help you leverage the latest capabilities in your projects.

Typed Class Constants

Previously, `PHP` class constants could not have explicit type declarations. With `PHP 8.3`, you can now specify types for class constants, enforcing stricter and safer code, especially in inheritance hierarchies and interfaces.

Example:

class Status {
    public const string ACTIVE = 'active';
    public const int    CODE   = 200;
}

If a subclass or implementing class tries to override the constant with a different type, `PHP` will throw a fatal error:

class BadStatus extends Status {
    // This will cause a fatal error:
    public const int ACTIVE = 1; // Error: Cannot use int as value for class constant Status::ACTIVE of type string
}

This feature also extends to `traits` and `enums`, ensuring type safety across all constant declarations.

Deep Cloning of Readonly Properties

Readonly properties, introduced in `PHP 8.1` and extended to classes in `8.2`, now support deep cloning. You can reinitialize readonly properties within the `__clone()` magic method, solving edge cases where deep copies of objects with readonly properties were previously impossible.

Example:

readonly class Post {
    public function __construct(
        public DateTime $createdAt,
    ) {}

    public function __clone() {
        $this->createdAt = new DateTime(); // Allowed in PHP 8.3
    }
}

This allows for safe, deep cloning of immutable objects, a boon for value objects and DTOs.

The `json_validate()` Function

`PHP 8.3` introduces `json_validate()`, a lightweight function to check if a string is valid `JSON`-without actually decoding it. This is more efficient than using `json_decode()` and checking for errors, especially for large payloads.

Example:

var_dump(json_validate('[1, 2, 3]')); // true
var_dump(json_validate('{1, 2, 3]')); // false

if (!json_validate($jsonString)) {
    throw new JsonException(json_last_error_msg(), json_last_error());
}

This function is declared in the global namespace and supports optional `$depth` and `$flags` parameters.

The `#[Override]` Attribute

The new `#[Override]` attribute is a developer tool for clarity and safety. It signals that a method is intended to override a parent method. If the parent method is removed or renamed, `PHP` will throw an error, preventing silent bugs.

Example:

abstract class ParentClass {
    public function doSomething(): void {}
}

class ChildClass extends ParentClass {
    #[Override]
    public function doSomething(): void {
        // Overriding parent method
    }
}

If `doSomething()` is removed from `ParentClass`, `PHP` will alert you during development.

New and Improved Functions

`PHP 8.3` adds several new functions and methods, enhancing string handling, multibyte support, and more.

| Function/Method                                 | Description                                      |
|-------------------------------------------------|--------------------------------------------------|
| `mb_str_pad()`                                  | Multibyte-safe string padding                    |
| `str_increment()`, `str_decrement()`            | Increment or decrement a string (like numbers)   |
| `stream_context_set_options()`                  | Set multiple context options at once             |
| `ReflectionMethod::createFromMethodName()`      | Create a ReflectionMethod from a method name     |
| `DOMElement::getAttributeNames()`, etc.         | New methods for DOM manipulation                 |
| `IntlCalendar::setDate()`, etc.                 | New methods for internationalization             |
| `socket_atmark()`                               | Check if socket is at out-of-band mark           |
| `ZipArchive::getArchiveFlag()`                  | Get archive flag from a ZipArchive               |

Example: Multibyte String Padding

echo mb_str_pad('テスト', 10, 'ー'); // Pads the Japanese word "テスト" to length 10

Performance and Internal Enhancements

  • `JIT` Improvements: Further optimizations to Just-In-Time compilation for faster code execution. 
  • Improved Garbage Collection: The new `gc_status()` function provides detailed garbage collector stats.
  • Optimized Array Handling: More efficient array operations, especially with negative indices.
  • New `INI` Settings: `zend.max_allowed_stack_size` allows for better stack size management.

Other Notable Changes

  • Anonymous Readonly Classes: You can now declare anonymous classes as readonly.
  • Dynamic Class Constant Fetch: Support for fetching class constants and `enum` members dynamically.
  • Error Handling Enhancements: More granular exceptions and improved `enum`-based error handling.

Conclusion

`PHP 8.3` is a robust update that brings type safety, developer ergonomics, and performance improvements. With features like typed class constants, deep cloning of readonly properties, `json_validate()`, and the `#[Override]` attribute, developers can write safer, clearer, and faster `PHP` code.


Written by X2Y.DEV
PHP 8.3 Web Dev

0%