Skip to content
English
On this page

PHP

Arrays

Atributes

php
class PostsController
{
    #[Route("/api/posts/{id}", methods: ["GET"])]
    public function get($id) { /* ... */ }
}

Destructuring

Skip elements:

php
$array = [1, 2, 3];

[, , $c] = $array;

// $c = 3

As well as destructure based on keys:

php
$array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
];

['c' => $c, 'a' => $a] = $array;

Constructor

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

Dealing with null

Null Coalescing

php
$temporaryPaymentDate = $invoice->paymentDate ??= Date::now();

Nullsafe Operator

php
$invoice
    ->getPaymentDate()
    ?->format('Y-m-d');
php
$object
    ?->methodA()
    ?->methodB()
    ?->methodC();

Enumerations

php
enum Status
{
    case Draft;
    case Published;
    case Archived;
}
function acceptStatus(Status $status) {...}

Enum methods

php
enum Status: int
 {
     case DRAFT = 1;
     case PUBLISHED = 2;
     case ARCHIVED = 3;

     public function color(): string
     {
         return match($this)
         {
             Status::DRAFT => 'grey',
             Status::PUBLISHED => 'green',
             Status::ARCHIVED => 'red',
         };
     }
 }

Exceptions

php
$error = fn($message) => throw new Error($message);
php
try {
    // …
} catch (SpecificException) {
    throw new OtherException();
}

Union types

php
class Number {
  public function __construct(
    private int|float $number
  ) {}
}

new Number('NaN'); // TypeError

Match expression

php
$message = match ($statusCode) {
    200, 300 => null,
    400 => 'not found',
    500 => 'server error',
    default => 'unknown status code',
};

Named Arguments

php
setcookie(
    name: 'test',
    expires: time() + 60 * 60 * 2,
);
php
$data = [
    'name' => 'test',
    'expires' => time() + 60 * 60 * 2,
];

setcookie(...$data);

Nullsafe operator

php
$country = $session?->user?->getAddress()?->country;

Readonly Properties

php
class BlogData
{
    public readonly Status $status;
  
    public function __construct(Status $status)
    {
        $this->status = $status;
    }
}

Short Closures

php
array_map(
    fn($x) => $x * $this->modifier,
    $numbers
);