PHP 8 est sorti il y a quelque temps maintenant. L’occasion d’introduire ce qui change dans la syntaxe 👇

Nouveautés PHP 8.0

Nullsafe operator

// PHP7
$address = $user->getAddress();
$country = $address ? $address->getCountry() : null;

// PHP8
$country = $user->getAddress()?->getCountry();

Manipulation de chaînes de caractères

// PHP7
$contains = strpos('Cette chaine contient pouet', 'pouet') !== false;

// PHP8
$contains = str_contains('blabla', 'bla');
$debut = str_starts_with('caillou chou pou', 'cai');
$fin = str_ends_with('caillou chou pou', 'pou');

Constructeurs

// PHP7
class User {
  public string $email;

  public function __construct(string $email) {
    $this->email = $email;
  }
}

// PHP8
class User {
  public function __construct(private string $email) {
    $this->email = $email;
  }
}

Arguments nommés

// PHP7
function foo(int $a, ?int $b = null, ?string $c = null, ?int $d = null) {

}

foo(2, null, null, 40);


// PHP8 - Evite de mettre des null pour rien, on met juste les paramètres obligatoires selon la signature de la fonction
foo(a:2, d: 40);

Typage d’arguments

Possible aussi sur le typage de la valeur de retour

// PHP8
public function bar(array|string $bla) : int | float {

}

Virgule finale

// PHP7
function foo(int $a, string $b) {
}

// PHP8 - Pouvoir ajouter de nouveaux arguments facilement
function foo(int $a, string $b,) {
}