Retour au blog
PHP

Les nouveautés de PHP 8

10 Feb 2024 8 min
PHP PHP8 Nouveautés

PHP 8 : une révolution pour le langage

PHP 8 apporte des améliorations majeures qui modernisent le langage et améliorent les performances grâce au compilateur JIT.

Named Arguments

// Avant
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);

// PHP 8
htmlspecialchars($string, double_encode: false);

Match Expression

$status = match($code) {
    200 => 'OK',
    301 => 'Redirect',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown',
};

Enums (PHP 8.1)

enum Status: string {
    case Active = 'active';
    case Inactive = 'inactive';
    case Pending = 'pending';

    public function label(): string {
        return match($this) {
            self::Active => 'Actif',
            self::Inactive => 'Inactif',
            self::Pending => 'En attente',
        };
    }
}

Fibers (PHP 8.1)

$fiber = new Fiber(function (): void {
    $value = Fiber::suspend('première pause');
    echo "Reçu : $value\n";
});

$result = $fiber->start(); // 'première pause'
$fiber->resume('données');

Readonly Properties (PHP 8.2)

class User {
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly DateTimeImmutable $createdAt = new DateTimeImmutable(),
    ) {}
}

Performances JIT

Le compilateur JIT améliore les performances de 2 à 3x pour les opérations intensives en CPU. Activez-le dans php.ini :

opcache.jit=1255
opcache.jit_buffer_size=100M