Middle
What new features and capabilities of PHP 8 can you highlight?
sobes.tech AI
Answer from AI
- Union Types: Allow specifying multiple possible types for an argument, return value, or property.
// Example of Union Type function processValue(int|float|string $value): int|float|string { return $value; } - Match expression: Similar to
switch, but is an expression that returns a value and has stricter comparisons (===).// Using match expression $result = match ($status) { 0 => 'Pending', 1 => 'Processing', 2 => 'Completed', default => 'Unknown status', }; - Named Arguments: Allow passing arguments to functions, methods, and constructors by their names, making calls more explicit, especially with many optional parameters.
// Using named arguments function createUser(string $name, string $email, bool $isActive = true) { // ...user creation logic } createUser(email: 'test@example.com', name: 'John Doe'); - Attributes (formerly Annotations): A structured way to add metadata to classes, methods, properties, functions, and constants.
// Example attribute #[Attribute] class Route { public function __construct(public string $path) { } } #[Route('/users')] class UserController { // ... } - Constructor Property Promotion: Simplifies declaring and initializing class properties directly in the constructor.
// Property Promotion class Point { public function __construct(public float $x, public float $y) { } } - Nullsafe operator (
?->): Allows calling methods or accessing properties in a chain, safely handling null values at intermediate steps.// Example nullsafe operator $country = $user?->getAddress()?->getCountry()?->getName(); - JIT (Just-In-Time) Compiler: An experimental feature aimed at improving performance by compiling frequently used code into machine code.
- Stringable interface: A new interface automatically implemented by classes with a
__toString()method. It indicates the ability to convert an object to a string.// Using Stringable interface function printStringable(Stringable $value) { echo $value; } - New
staticreturn type: Indicates that a method will return an instance of the class it was called on (more precise thanself).// New static return type class ParentClass { public function create(): static { return new static(); } }
| Feature | Brief Description |
|---|---|
| Union Types | Specify multiple possible types for a variable/return/property. |
| Match expression | A selection expression similar to switch. |
| Named Arguments | Passing arguments by name. |
| Attributes | Metadata for code. |
| Constructor Property Promotion | Declare/initialize properties in constructor. |
Nullsafe operator (?->) |
Safe access to properties/methods in a chain with null. |
| JIT Compiler | Experimental compiler for performance. |
| Stringable interface | Interface for objects that can be converted to a string. |
New static return type |
Specify return of an instance of the calling class. |