Skip to content
Type Declarations
step 1/6

Reading — step 1 of 6

Learn

~1 min readModern PHP

PHP 7+ supports parameter types, return types, and (PHP 7.4+) typed properties. Use them everywhere.

<?php
declare(strict_types=1);    // makes type checks strict — recommended

function add(int $a, int $b): int {
    return $a + $b;
}

class User {
    public string $name;
    public int $age;
    public ?string $email;        // nullable
}

Without strict_types, PHP coerces — add("5", "10") becomes add(5, 10). With strict_types, it throws TypeError.

Type modifiers:

  • ?T — nullable (T or null)
  • T|U — union type (PHP 8+)
  • iterable, callable, mixed, void, never
  • Class names as types: function process(User $u)

Property type rules:

  • Properties must be initialized OR be nullable
  • private string $x = "";
  • private string $x; errors at construction unless set in __construct

Constructor property promotion (PHP 8+) — declare and assign in one go:

class Point {
    public function __construct(
        public readonly float $x,
        public readonly float $y,
    ) {}
}

Judge0 ships PHP 7.4 — promotion isn't available there, but typed properties are.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Type Declarations — PHP Intermediate