PHP 8.2 Features: What's New and How to Use Them

Explore PHP 8.2 new features including readonly classes, disjunctive normal form types, sensitive parameter redaction, and performance improvements.

S

StalkTechie

Author

September 2, 2025
1676 views

PHP 8.2 Features: What's New and How to Use Them

PHP 8.2, released in December 2022, brought a mix of developer-friendly enhancements, security tweaks, and under-the-hood optimizations that make your code cleaner and safer. If you're upgrading from 8.1 or earlier, it's a smooth ride with deprecations you can prep for. Let's break down the highlights-like readonly classes and better types-with real-world examples. Think of this as your quick upgrade cheat sheet; it boosts immutability, refines error handling, and even speeds things up a bit.

Readonly Classes: Immutable Objects Made Easy

Building on PHP 8.1's readonly properties, 8.2 lets you mark an entire class as readonly. This auto-applies readonly to all properties, perfect for data transfer objects (DTOs) where you don't want accidental mutations. No more typing readonly on every prop-saves boilerplate and enforces immutability at the class level.


readonly class UserDTO
{
    public function __construct(
        public string $name,
        public int $age,
        public string $email
    ) {}
}

// Usage
$user = new UserDTO('Ali', 30, 'ali@example.com');
echo $user->name;  // Works

$user->name = 'New Name';  // Fatal error: Cannot modify readonly property
    

Caveat: All properties must be typed (no untyped ones allowed), and it works with promoted props. Great for APIs or value objects-pair it with records in other langs' style. Pro tip: If you extend a readonly class, the child inherits the readonly trait, keeping consistency.

Disjunctive Normal Form (DNF) Types: Smarter Unions and Intersections

DNF types let you combine intersections (&) and unions (|) in a "normal form" for more expressive type declarations. It's like saying "this param is (A&B) or (C&D)"-super useful for complex APIs without messy comments or wrappers.


function processData((A&B)|(C&D) $param): void { ... }

// Example interfaces
interface A { public function foo(); }
interface B { public function bar(); }
interface C { public function baz(); }
interface D { public function qux(); }

// Valid: Implements A and B, or C and D
class Valid implements A, B { ... }  // Or C, D
    

In practice, this shines in libraries (e.g., Symfony or Laravel components) for stricter contracts. It validates at runtime too-mismatches throw TypeError. Human note: Start using in method params for better autocomplete in IDEs like PhpStorm; it catches bugs early without phpstan hacks.

Sensitive Parameter Redaction: Hide Secrets in Traces

Ever had passwords or tokens leak in var_dumps or error logs? The new #[\SensitiveParameter] attribute redacts values in stack traces, making debugging safer in production.


function login(#[\SensitiveParameter] string $password) {
    throw new Exception('Login failed');  // Password won't show in trace
}

login('secret123');  // In trace: $password = '[REDACTED]'
    

Applies to closures and methods too. Real-world win: Protects API keys in frameworks. Combine with assert() or env vars-don't rely solely on this, but it's a nice safety net for those "oh no" moments.

New Random Extension: Secure, Simple Randomness

Goodbye rand() inconsistencies; PHP 8.2 introduces a new OO random extension for cryptographically secure randomness. It's engine-agnostic and easier to mock in tests.


$random = new Random\Randomizer();

echo $random->getInt(1, 100);  // Random int
echo $random->shuffleString('abcde');  // Shuffled

// Secure bytes
$bytes = (new Random\Randomizer(new Random\Engine\Secure()))->getBytes(16);
    

Use for OTPs, tokens, or shuffling-faster and more secure than random_int() chains. Tip: Swap engines for testing (e.g., predictable sequences) without changing code.

Performance and Minor Wins

  • Faster Fibers: Improved async handling in libs like Amp or Swoole-up to 10% speedup in I/O bound tasks.
  • Dynamic Class Constant Fetch: Now allowed: class::{$constName} for meta-programming.
  • Enum Improvements: From 8.1, now support DNF in method params.
  • Deprecations: ${} in strings is dynamic no more-use curlies sparingly to avoid future breaks.

Benchmarks show ~5% overall JIT gains in opcache-heavy apps. Run php -v and test with phpbench for your codebase.

Migration and Best Practices

Upgrade via Composer or brew-check deprecations with phpstan or Rector for auto-fixes. In Laravel/Symfony, update vendors and test auth flows (sensitive params help here). Real talk: Readonly classes changed my DTO game-less bugs in data layers. For teams, adopt gradually; focus on types for long-term wins. If issues, PHP's backward compat is solid, but pin versions in docker: php:8.2-fpm.

PHP 8.2 keeps evolving the language toward modern, safe coding. It's not revolutionary like 8.0, but these tweaks make daily dev smoother. Dive in, experiment, and share your wins on PHP subreddit-community's gold for edge cases!

Share this post:

Related Articles

Discussion

0 comments

Please log in to join the discussion.

Login to Comment