New Features in PHP 8.1: A Practical Guide with Code Examples

Home / Blog / New Features in PHP 8.1: A Practical Guide with Code Examples


`PHP 8.1` is a major update that introduces several powerful features and improvements designed to make your code more robust, expressive, and performant. Below, we explore the most notable additions, complete with practical code examples.

Enums: Native Enumerations

`PHP 8.1` introduces native enumerations, allowing you to define a set of possible values for a variable, improving type safety and code clarity.

enum Status {
    case Draft;
    case Published;
    case Archived;
}

// Usage
function setStatus(Status $status) {
    // ...
}

$postStatus = Status::Draft;
setStatus($postStatus);

Enums can also have methods and backed values (`string` or `int`), making them versatile for many use cases.

`readonly` Properties

`readonly` properties can be assigned once and then become immutable, ensuring that certain values in your objects remain constant after initialization.

class User {
    public readonly int $id;

    public function __construct(int $id) {
        $this->id = $id;
    }
}

$user = new User(42);
// $user->id = 99; // Error: Cannot modify readonly property

`readonly` properties are ideal for value objects and entities where immutability is desired.

`Fiber`s: Lightweight Concurrency

`Fiber`s provide a foundation for asynchronous programming by allowing you to pause and resume blocks of code, similar to coroutines or lightweight threads.

$fiber = new Fiber(function (): void {
    echo "Hello, ";
    Fiber::suspend();
    echo "World!";
});

$fiber->start();
echo "Fiber ";
$fiber->resume();
// Output: Hello, Fiber World!

This feature is particularly useful for frameworks and libraries that implement cooperative `multitasking` or `asynchronous` I/O.

`never` Return Type

The new `never` return type indicates that a function will not return a value and will instead terminate script execution (e.g., by throwing an exception or calling `exit()`).

function redirect(string $url): never {
    header("Location: $url");
    exit();
}

redirect('/dashboard');
// Any code here is unreachable

This helps static analysis tools understand code flow and improves code correctness.

Array Unpacking with String Keys

`PHP 8.1` allows array unpacking to work with arrays that have string keys, not just numeric ones.

$array1 = ['a' => 1];
$array2 = ['b' => 2];
$result = [...$array1, ...$array2];
// ['a' => 1, 'b' => 2]

This makes merging associative arrays more convenient and expressive.

Explicit Octal Numeral Notation

You can now write octal numbers using the `0o` or `0O` prefix, improving clarity and consistency with other numeric literals.

$octal = 0o16; // 14 in decimal

This is especially helpful for developers familiar with other programming languages.

New Functions and Improvements

  • `array_is_list()`: Checks if an array is a list (sequential numeric keys starting from `0`).
$list = ["a", "b", "c"];
var_dump(array_is_list($list)); // true

`fsync()` and `fdatasync()`: Ensure data is physically written to disk.

$file = fopen("sample.txt", "w");
fwrite($file, "Some content");
fsync($file);
fclose($file);

`MurmurHash3` and `xxHash` Support: New fast, non-cryptographic hash algorithms are now available for general-purpose hashing.

Other Notable Features

  • First-class Callable Syntax: You can now use the `foo(...)` syntax to reference `callables` directly.
  • Final Class Constants: Prevent child classes from overriding constants by marking them as `final`.
  • Intersection Types: Combine multiple type constraints for parameters and properties.
  • Performance Improvements: Inheritance cache and other optimizations enhance overall performance.

Conclusion

`PHP 8.1` marks a significant step forward for the language, offering features that enhance type safety, concurrency, and developer ergonomics. Whether you're building modern web applications or maintaining legacy code, these new capabilities can help you write cleaner, safer, and more efficient `PHP`.


Written by X2Y.DEV
PHP 8.1 Web Dev

0%