PHP 8 cheatsheet

PHP 8: Types and functions

10 common PHP 8 tasks.

Turn on strict typing

Put this on the first line of a file so scalar type declarations aren't silently converted.

<?php

declare(strict_types=1);

Declare types

Type parameters and return values. ?string means string or null.

function greet(string $name, ?string $title = null): string
{
    return trim("$title $name");
}

Use union types

Accept more than one type for a parameter.

function id(int|string $value): int|string
{
    return $value;
}

Call with named arguments

Name arguments to skip optional ones and make calls readable.

$result = htmlspecialchars($text, double_encode: false);

Write an arrow function

A short closure that captures outer variables automatically.

$doubled = array_map(fn ($n) => $n * 2, $numbers);

Declare properties in the constructor

Define and assign properties from constructor parameters.

class User
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
    ) {}
}

Define an enum

A fixed set of named values, optionally backed by strings or integers.

enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
}

$status = Status::from('draft');

Use match instead of switch

Match with strict comparison. It returns a value and throws if nothing matches.

$label = match ($status) {
    Status::Draft => 'Draft',
    Status::Published => 'Live',
};

Call methods on possible nulls

Short-circuit to null instead of an error.

$city = $user?->address?->city;

Provide a default

Use a default when a value is null or missing.

$page = $_GET['page'] ?? 1;

Was this page helpful?