In PHP, how do I index objects with PHP 8+ features?

In PHP 8 and later versions, you can index objects using various features like the nullsafe operator, property promotion, and more. Here's a brief overview of how to work with objects and arrays in a more efficient manner with PHP 8+.

PHP 8 introduced a number of enhancements to object handling that made it easier to manipulate and access object properties directly.

// Example of property promotion in PHP 8 class User { public function __construct( public string $name, public string $email, public array $roles = [] ) {} } // Create a new User object $user = new User("John Doe", "john@example.com", ["admin", "editor"]); // Accessing the properties directly echo $user->name; // Outputs: John Doe echo $user->email; // Outputs: john@example.com print_r($user->roles); // Outputs: Array ( [0] => admin [1] => editor ) // Using the nullsafe operator $emailDomain = $user->roles[0]->getEmail() ?? 'Email not available'; // Avoids errors when properties are null

PHP 8 Objects Nullsafe Operator Property Promotion PHP Features PHP Arrays