16.2 — Cheatsheet PHP 8.0 → 8.4
« C’est arrivé en quelle version ? » — le mémo par version. Détails en Partie 2.
Par version
PHP 8.0 (nov. 2020)
| Fonctionnalité | Exemple |
|---|---|
| Types union | function f(int|string $x) |
| Arguments nommés | new Booking(status: X, seats: 2) |
| Attributs | #[Route('/x')] |
| Promotion de constructeur | public function __construct(private int $id) {} |
match | $r = match($s) { A => 1, default => 0 }; |
| Nullsafe | $a?->b()?->c |
str_contains / str_starts_with / str_ends_with | str_contains($s, 'x') |
throw comme expression | $x = $a ?? throw new Exception(); |
mixed, JIT | — |
PHP 8.1 (nov. 2021)
| Fonctionnalité | Exemple |
|---|---|
| Enums | enum Status: string { case A = 'a'; } |
Propriétés readonly | public readonly int $id; |
| First-class callable | $fn = strlen(...); |
| Types intersection | Countable&Traversable |
never | function fail(): never { throw ... } |
new dans valeurs par défaut | function f($x = new Foo()) |
| Fibers | (bas niveau, rarement direct) |
PHP 8.2 (déc. 2022)
| Fonctionnalité | Exemple |
|---|---|
Classes readonly | final readonly class Money {} |
| Types DNF | (A&B)|null |
null/false/true autonomes | function f(): false |
| Constantes dans les traits | — |
PHP 8.3 (nov. 2023)
| Fonctionnalité | Exemple |
|---|---|
| Constantes de classe typées | const int MAX = 10; |
#[\Override] | #[\Override] public function x() {} |
json_validate() | json_validate($s) |
| Clonage/readonly assouplis | — |
PHP 8.4 (déc. 2024)
| Fonctionnalité | Exemple |
|---|---|
| Property hooks | public string $name { get => ...; set => ...; } |
| Visibilité asymétrique | public private(set) int $id; |
new sans parenthèses (chaînage) | new Foo()->bar() → new Foo->bar() |
#[\Deprecated] | #[\Deprecated] function old() {} |
| Objets lazy | — |
array_find, array_any, array_all | array_find($a, $fn) |
Syntaxe survie (dev JS)
| Besoin | PHP |
|---|---|
| Concaténer | 'a' . 'b' (pas +) |
| Égalité stricte | === (jamais ==) |
| Membre objet | $obj->prop |
| Statique / enum | Classe::CONST, Status::A |
| Interpolation | "Hi $name" / "{$obj->p}" |
| Fléchée | fn($x) => $x * 2 |
| Closure | function () use ($y) {} |
| Tableau/map | [1,2,3] / ['a' => 1] (tous deux array) |
| En-tête de fichier | declare(strict_types=1); |
Correspondances TS → PHP (rappel)
| TypeScript | PHP |
|---|---|
arr.map(f) | array_map($f, $arr) |
arr.filter(f) | array_filter($arr, $f) |
arr.reduce(f, i) | array_reduce($arr, $f, $i) |
JSON.parse(s) | json_decode($s, true) |
JSON.stringify(x) | json_encode($x) |
new Date() | new \DateTimeImmutable() |
a?.b | $a?->b |
a ?? b | $a ?? $b |
T[] | array + /** @var T[] */ (PHPStan) |
Suivant : 16.3 — Cheatsheet Symfony CLI.