Sobes.tech
Junior — Middle

What new features appeared in PHP 8 compared to previous versions?

sobes.tech AI

Answer from AI

PHP 8 introduced many new features and improvements over previous versions:

  • JIT compilation (Just-In-Time) — improves performance by compiling bytecode into machine code at runtime.
  • Union Types — now you can specify multiple types for parameters and return values, for example: function foo(int|float $num).
  • Attributes (annotations) — a new syntax for adding metadata to classes, methods, etc., using #[Attribute].
  • Constructor Property Promotion — a concise syntax for declaring and initializing properties directly in the constructor.
  • Match expression — a more powerful and safer alternative to switch, returning a value.
  • Nullsafe operator (?->) — allows safe access to properties and methods of objects that may be null.
  • Strict typing for mixed and improvements in types.
  • New functions and syntax improvements, such as str_contains(), str_starts_with(), str_ends_with().

Example of using union types and constructor property promotion:

class User {
    public function __construct(
        private int|string $id,
        private string $name
    ) {}
}

function process(User|int $userOrId) {
    // ...
}

PHP 8 significantly enhanced the language's expressiveness and performance.