Skip to content

Instantly share code, notes, and snippets.

@fazni
Last active December 31, 2021 15:31
Show Gist options
  • Save fazni/51a6eb136143b5011e76bada64f34b88 to your computer and use it in GitHub Desktop.
Save fazni/51a6eb136143b5011e76bada64f34b88 to your computer and use it in GitHub Desktop.
Cheat sheet - New PHP 8 features

1. Named arguments

<?php
// Positional arguments.
$pieces = explode('-', 'piece1-piece2-piece3');
 
// Named arguments.
$pieces = explode(delimiter: '-', string: 'piece1-piece2-piece3');
// or
$pieces = explode(string: 'piece1-piece2-piece3', delimiter: '-');

PHP RFC: Named Arguments

2. Nullsafe operator ?->

<?php

$street_number =  null;

$current_user = \Drupal::currentUser();
 
if ($current_user !== NULL) {
    $account = $current_user->getAccount();
 
    if ($account !== NULL) {
        $address = $account->getAddress();
 
        if ($address !== NULL) {
            $street_number = $address->getStreetNumber();
        }
    }
}

Replace by

<?php
 $street_number = \Drupal::currentUser()?->getAccount()?->getAddress()?->getStreetNumber();

PHP RFC: Nullsafe operator

3. String contains, string starts with and string ends with functions

<?php

str_contains("abc", "a"); // true
str_contains("abc", "d"); // false
 
// $needle is an empty string
str_contains("abc", "");  // true
str_contains("", "");     // true

PHP RFC: str_contains

<?php

str_starts_with('Said', 'Sa'); // returns TRUE 
str_ends_with('EL FAZNI', 'SA'); // returns FALSE

PHP RFC: Add str_starts_with() and str_ends_with() functions

4. Constructor property promotion

PHP7

<?php

class Point {
    public float $x;
    public float $y;
    public float $z;
 
    public function __construct(
        float $x = 0.0,
        float $y = 0.0,
        float $z = 0.0,
    ) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }
}

PHP8

<?php

class Point {
    public function __construct(
        public float $x = 0.0,
        public float $y = 0.0,
        public float $z = 0.0,
    ) {}
}

PHP RFC: Constructor Property Promotion

4. throw Expression

PHP RFC: throw expression

Weak Maps https://wiki.php.net/rfc/weak_maps Attributes v2 https://wiki.php.net/rfc/attributes_v2

5. Named arguments

PHP8

<?php

function foo(string $a, string $b, ?string $c = null, ?string $d = null) 
{ /* … */ }

foo(
    b: 'value b', 
    a: 'value a', 
    d: 'value d',
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment