A type declaration tells PHP what kind of value a parameter must be. It catches mistakes early and makes functions easier to understand.
<?php
function repeatText(string $text, int $times): string
{
return str_repeat($text, $times);
}
echo repeatText("Ha", 3);
HaHaHa
string $text means $text must be a string. int $times means a whole number.
Types you can use
| Type | Meaning |
|---|---|
int | Whole number |
float | Decimal number |
string | Text |
bool | true or false |
array | An array |
callable | Something that can be called |
iterable | An array or anything you can foreach |
object | Any object |
mixed | Anything at all |
ClassName | An object of that class |
What happens with the wrong type
By default, PHP converts a value if it can ("5" becomes 5) and throws a TypeError if it cannot.
<?php
function double(int $n): int
{
return $n * 2;
}
echo double("5") . "\n"; // converted
try {
echo double("abc"); // cannot be converted
} catch (TypeError $e) {
echo "TypeError: " . $e->getMessage();
}
10
TypeError: double(): Argument #1 ($n) must be of type int, string given, called in /path/to/index.php on line 10
Add declare(strict_types=1); to stop conversions as well. See Strict Typing.
Nullable types
A ? before the type allows null too.
<?php
function greet(?string $name): string
{
return "Hello, " . ($name ?? "guest");
}
echo greet("Mira") . "\n";
echo greet(null);
Hello, Mira
Hello, guest
Union types (PHP 8.0+)
A parameter can accept more than one type, separated by |.
<?php
function showId(int|string $id): string
{
return "ID: " . $id;
}
echo showId(42) . "\n";
echo showId("A-17");
ID: 42
ID: A-17
Class types
<?php
class Product {}
function describe(Product $product): string
{
return "A product object";
}
echo describe(new Product());
A product object
Why you should use them
- Errors show up at the function call, not three steps later.
- Your editor can warn you about wrong calls.
- Anyone reading the function sees what it needs without a comment.