New Features in PHP 8.2: A Comprehensive Guide with Code Examples
`PHP 8.2` is a major update that brings a suite of modern features, type system improvements, and quality-of-life enhancements for developers. Below, we’ll explore the most significant new features in `PHP 8.2`, complete with code examples to help you get started.
`Readonly` Classes
`PHP 8.1` introduced `readonly` properties, but `PHP 8.2` takes this further with `readonly` classes. When you declare a class as `readonly`, all its properties become `readonly` by default-they can only be written once, usually in the constructor, and cannot be changed afterward. This is particularly useful for data transfer objects and value objects.
// PHP 8.1 style class BlogData { public function __construct( public readonly string $title, public readonly Status $status, public readonly ?DateTimeImmutable $publishedAt = null, ) {} } // PHP 8.2 style readonly class BlogData { public function __construct( public string $title, public Status $status, public ?DateTimeImmutable $publishedAt = null, ) {} }
`Readonly` classes cannot have static properties, dynamic properties, or `untyped` properties.
`Null`, `False`, and `True` as Standalone Types
`PHP 8.2` allows `null`, `false`, and true to be used as standalone types in type declarations. Previously, these could only be used in union types. Now, you can specify a parameter, `return` type, or `property` as accepting only `null`, `true`, or `false`.
function acceptNull(null $value): null { return $value; } function alwaysTrue(): true { return true; }
This change brings greater precision and clarity to your type declarations.
Disjunctive Normal Form (`DNF`) Types
`DNF` types allow you to combine union and intersection types in a standardized way-essentially, an `OR` of `AND`s. This makes complex type declarations more expressive and easier for the parser to handle.
interface A {} interface B {} interface D {} function process((A&B)|D $input) { // $input must implement both A and B, or just D }
`DNF` types ensure that each segment is unique and not a strict subset of another, preventing redundancy and confusion.
Sensitive Parameter Redaction in Back Traces
To improve security, `PHP 8.2` introduces the `#[\SensitiveParameter]` attribute. When applied to a function parameter, its value is redacted from stack traces and error messages, helping prevent accidental leaks of sensitive data such as passwords.
function login(string $username, #[\SensitiveParameter] string $password) { // If an error occurs, $password will be redacted in the trace }
Built-in functions like `password_hash` and `password_verify` already use this attribute.
New Random Extension and OOP `Randomizer`
`PHP 8.2` introduces a new random extension, which consolidates all random number generation functionality and adds a new object-oriented API. The `Random\Randomizer` class allows you to select different random engines, making it easier to swap engines for testing or security.
use Random\Engine\Secure; use Random\Engine\Mt19937; use Random\Randomizer; $isProduction = true; $rng = $isProduction ? new Secure() : new Mt19937(1234); $randomizer = new Randomizer($rng); echo $randomizer->shuffleString('foobar');
Legacy random functions (`rand`, `random_int`, etc.) remain available, but the new API provides more flexibility and security.
New `MySQLi` Execute Query Function
Running parameterized queries with `MySQLi` is now easier thanks to the new `mysqli_execute_query()` function and `mysqli::execute_query` method. These allow you to `prepare`, `bind`, and `execute` queries in a single step.
foreach ($db->execute_query( 'SELECT * FROM user WHERE name LIKE ? AND type_id IN (?, ?)', [$name, $type1, $type2] ) as $row) { print_r($row); }
This streamlines database code and reduces the risk of `SQL injection`.
Other Notable Improvements
- Fetch `enum` Properties in `const` Expressions: You can now use `->` and `?->` to fetch `enum` properties in constant expressions, enabling more flexible array keys and values.
- New Utility Functions:
- `ini_parse_quantity()`: Parses `INI`-style size strings (e.g., "256M") into bytes.
- `memory_reset_peak_usage()`: Resets the peak memory usage counter.
- `curl_upkeep()`: Adds support for the `curl_easy_upkeep()` function in `libcurl`.
- Regex No-Capture Modifier: The `/n` modifier in `preg_*` functions disables capturing groups for more efficient regex matching.
Deprecations in `PHP 8.2`
- Dynamic Properties: Assigning properties not declared in the class is now deprecated.
- `${}` String Interpolation: Deprecated due to confusion and rare usage.
- Partially Supported Callables: Deprecated in preparation for `PHP 9.0`.
`PHP 8.2` continues `PHP`'s evolution toward a safer, more expressive, and developer-friendly language. Whether you’re building robust APIs, secure applications, or high-performance web services, these new features provide powerful tools to write cleaner and more maintainable code.
0%