Skip to content
Justice Tech School

Type Declarations and Union Types

Declare parameter, return and property types. Union types int|string, nullable ?int, mixed, never and static return types make intent clear. strict_types stops silent conversions.

Example
declare(strict_types=1);
function id(int|string $v): string { return (string) $v; }
function find(int $n): ?string { return $n === 1 ? "one" : null; }
echo id(5), id("a"), " ", find(2) ?? "none", "\n";
try { id([]); } catch (TypeError $e) { echo "TypeError\n"; }

Result

5a none
TypeError

Exercise

Nullable int.

function f(int $n) {}

Quiz Test

What does ?int mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.