Skip to content

PHP Tutorial Functions

Type Declarations

Lesson 105 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

A type declaration tells PHP what kind of value a parameter must be. It catches mistakes early and makes functions easier to understand.

index.php
PHP
<?php
function repeatText(string $text, int $times): string
{
    return str_repeat($text, $times);
}

echo repeatText("Ha", 3);
Output
OUTPUT
HaHaHa

string $text means $text must be a string. int $times means a whole number.

Types you can use

TypeMeaning
intWhole number
floatDecimal number
stringText
booltrue or false
arrayAn array
callableSomething that can be called
iterableAn array or anything you can foreach
objectAny object
mixedAnything at all
ClassNameAn 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.

index.php
PHP
<?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();
}
Output
OUTPUT
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.

index.php
PHP
<?php
function greet(?string $name): string
{
    return "Hello, " . ($name ?? "guest");
}

echo greet("Mira") . "\n";
echo greet(null);
Output
OUTPUT
Hello, Mira
Hello, guest

Union types (PHP 8.0+)

A parameter can accept more than one type, separated by |.

index.php
PHP
<?php
function showId(int|string $id): string
{
    return "ID: " . $id;
}

echo showId(42) . "\n";
echo showId("A-17");
Output
OUTPUT
ID: 42
ID: A-17

Class types

index.php
PHP
<?php
class Product {}

function describe(Product $product): string
{
    return "A product object";
}

echo describe(new Product());
Output
OUTPUT
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.
lightbulb
Type everything you write
Add types to every parameter and return value in new code. It costs a few seconds and saves hours of debugging.