Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 147 ยท Functions

Type Declarations

Learn PHP type declarations for parameters and return values - scalar, nullable, union, intersection and DNF types, mixed, void, never, static and strict_types.

PHP is dynamically typed: a variable can hold an integer now and a string later. Functions, though, almost always expect specific kinds of values. A type declaration writes that expectation into the signature, like function total(array $prices): float. PHP then checks every call, and a wrong value stops the program with a clear TypeError instead of silently producing garbage three functions later.

Types are also documentation that can't go out of date, and they let editors and static analyzers (PHPStan, Psalm) catch bugs before the code even runs. Modern PHP code declares types on nearly every parameter, return value and property. This lesson covers every kind of type you can write, from int to DNF types like (A&B)|null, and explains exactly what declare(strict_types=1) changes.

It builds on Parameters and Arguments. For the deeper theory (variance, generics in PHPDoc), see The PHP Type System in Depth later in the course.

Parameter and return types

Write a type before a parameter name, and a return type after the parameter list with a colon:

PHP Types on parameters and return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 10, GH and bool(false). Note that rectangleArea(2.5, 4) passed an integer 4 to a float parameter. That's always allowed, even in strict mode: an int widens to a float without losing anything.

The basic types you can use:

Type Accepts
int, float, string, bool scalar values
array any array
callable anything you can call (parameters only, not properties)
iterable arrays and Traversable objects (since 8.2 it means array|Traversable)
object any object
a class or interface name instances of it or of a subclass/implementation
self, parent, static the current class, its parent, the called class (static only as a return type)
mixed (8.0) anything, including null
null, false, true exactly that value (standalone since 8.2)
void, never return types only (see below)

Coercive mode vs strict_types

By default, PHP runs in coercive mode: if a scalar argument has the wrong type but can be converted sensibly, PHP converts it. With declare(strict_types=1); at the very top of a file, calls made from that file must pass exactly the right scalar type (except the int-to-float widening). Compare them:

PHP Coercive mode converts scalars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first three calls print int(42), int(14) and int(2). The last one fails because 'twenty' isn't numeric at all:

TEXT
TypeError: double(): Argument #1 ($n) must be of type int, string given, called in main.php on line 14

Now the same function in strict mode:

PHP strict_types rejects the wrong scalar type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

double(21) works, but '21' is now rejected:

TEXT
TypeError: double(): Argument #1 ($n) must be of type int, string given, called in main.php on line 12

Strict mode turns "it happened to work" into "it's correct". A string from a form or a CSV file must be converted on purpose, for example with (int) $_POST['age'] after validating it, rather than drifting through your functions as a string.

What strict_types actually affects

The rules surprise many developers, so read them carefully:

  • It must be the first statement in the file (only comments and the opening tag before it).
  • It's per file, and it depends on the calling file. A function declared in a strict file but called from a non-strict file still gets coercive behavior for that call. What matters is where the call is written.
  • It covers calls to built-in functions too: in strict mode strlen(123) throws a TypeError.
  • It covers return values: a function in a strict file returning '5' from : int fails.
  • It covers typed properties assigned in that file.
  • It does not change operators or comparisons: '5' + 3 is still 8, and == still juggles types. See Type Juggling and Casting.

Put declare(strict_types=1); at the top of every PHP file you write. Most modern projects and frameworks do, and coding-standard tools can add it automatically.

Even in coercive mode, PHP 8.1+ warns about lossy conversions: passing 2.5 to an int parameter still works, but emits "Deprecated: Implicit conversion from float 2.5 to int loses precision". That's one more reason to use strict mode and convert explicitly.

Nullable types and null defaults

?Type means "this type or null". It's shorthand for the union Type|null:

PHP Nullable parameters and returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints string(5) "Linus", NULL, Hello, Ada! and Hello, guest! twice. A nullable return type like ?string is honest about "might not find it", and callers who forget the null case get flagged by static analyzers.

Nullable and optional are different things. ?string $name without a default is still required: the caller must pass something, even if that something is null. Adding = null makes it optional too.

Union types (PHP 8.0)

A union type A|B accepts any of the listed types:

PHP Union types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is #00042, #AB-7, int(8080) and bool(false). Inside the function you narrow the union with checks like is_int(), is_string() or instanceof.

The false type exists mostly for legacy-style APIs: many built-in functions return a value or false on failure (strpos, file_get_contents). For new code, prefer ?Type or throwing an exception. PHP rejects redundant unions at compile time: int|int or ?string|null are errors.

Intersection and DNF types

An intersection type A&B (PHP 8.1) requires a value that is all of the listed class or interface types at once. It only makes sense with class and interface names:

PHP Intersection types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

ArrayObject implements both Countable and IteratorAggregate, so the first call prints 3 items: kiwi, fig, plum. ArrayIterator is Countable and an Iterator, but not an IteratorAggregate, so the second call is rejected with a TypeError that names the expected type Countable&IteratorAggregate.

DNF types (Disjunctive Normal Form, PHP 8.2) combine both: a union of intersections, with each intersection in parentheses. The most common real use is making an intersection nullable:

PHP
function render((Countable&Traversable)|null $rows): string { /* ... */ }

You'll write these rarely, but you'll meet them in framework code. Interfaces themselves are covered in Abstract Classes and Interfaces.

mixed: anything at all

mixed (PHP 8.0) accepts every value, including null. It's equivalent to array|bool|callable|int|float|null|object|resource|string. Because it already includes null, writing ?mixed is an error.

Use mixed when a function genuinely accepts anything, like a debugging helper or a cache that stores any value. Writing mixed explicitly is still better than writing no type: it tells readers "I thought about it, and anything is fine".

Return-only types: void, never, static

void

void means the function returns nothing. It can use return; to exit early, but not return null; or any value. Calling it still gives null if someone uses the result.

never (PHP 8.1)

never means the function never returns normally: it always throws an exception or ends the script with exit. Static analyzers then know code after the call is unreachable.

PHP void and never return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints [log] starting, 2.5 and Caught: Division by zero. If a never function accidentally finishes, PHP throws TypeError: fail(): never-returning function must not implicitly return.

static

static as a return type means "an instance of the class the method was called on", which matters for inheritance and fluent methods. You'll use it in Static Properties and Methods.

When types fail: TypeError

Every type violation throws a TypeError, which is an Error (not an Exception), so a plain catch (Exception $e) won't catch it. In practice you rarely catch TypeError: it signals a bug in the calling code, and the fix is to correct the call. The message tells you everything: the function, the argument number and name, the expected type, the given type, and the line of the call.

Return types are checked too, and the message points at the function that broke its promise:

TEXT
TypeError: price(): Return value must be of type float, string returned

You'll learn how to handle errors properly in Exceptions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a file WITHOUT strict_types, what does function f(int $n) { return $n; } var_dump(f("8")); print?

    Coercive mode converts the numeric string "8" to the int 8 before the function runs.
  2. 2. With declare(strict_types=1);, which call to function area(float $r): float is allowed?

    Strict mode still allows int to float widening. Strings, null and booleans are rejected.
  3. 3. Which statement about ?string $name (no default value) is true?

    Nullable means null is an accepted value; it doesn't make the parameter optional. Add = null for that.
  4. 4. Which return type fits a function that always throws an exception?

    never (PHP 8.1) says the function never returns normally. void functions do return, just without a value.
  5. 5. strict_types is enabled in a.php (which defines a function) but not in b.php (which calls it). Which mode applies to the call?

    strict_types follows the file where the call is written. Return values are checked using the mode of the file that defines the function.

Summary

  • Type declarations go before parameters (int $n) and after the parameter list for returns (: string). Violations throw TypeError.
  • Without strict mode, PHP coerces scalars ('21' becomes 21). declare(strict_types=1); makes calls from that file require exact scalar types, except int to float. Use it in every file.
  • ?Type adds null; a nullable parameter is still required unless it has a default.
  • Union A|B (8.0), intersection A&B (8.1) and DNF (A&B)|null (8.2) types combine types; mixed accepts anything.
  • void returns nothing, never (8.1) never returns normally, static returns the called class.
  • TypeError is an Error, not an Exception: it signals a bug to fix, not a condition to handle.

Next: Variable Scope