Docs/PHP/Type Declarations

PHP Type Declarations

Fitur (PHP 7+)

  • Parameter types
  • Return types
  • Property types (PHP 7.4+)
  • Union types: int|string (PHP 8)
  • Nullable: ?string
  • declare(strict_types=1)
index.php
Try It →
<?php
declare(strict_types=1);

// Parameter + return types
function add(int $a, int $b): int {
    return $a + $b;
}
echo "add(3, 5): " . add(3, 5) . "
";

// Nullable
function findUser(?int $id): ?string {
    if ($id === null) return null;
    return "User #$id";
}
echo "findUser(1): " . findUser(1) . "
";
echo "findUser(null): " . var_export(findUser(null), true) . "

";

// Union types (PHP 8)
function format(int|float $num): string {
    return number_format($num, 2);
}
echo "format(42): " . format(42) . "
";
echo "format(3.14): " . format(3.14) . "

";

// Class with typed properties
class Product {
    public function __construct(
        public readonly string $name,
        public readonly float $price,
        public readonly ?string $description = null
    ) {}
}

$p = new Product("Widget", 29.99);
echo "Product: $p->name - \$$p->price";
?>