Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

TypeError

The error of a mismatched argument or return type.

Syntax

catch (TypeError $e) { … }

Return value

TypeErrorThe error object.

Examples

An array instead of a string:

<?php
 
function shout(string $text): string
{
    return strtoupper($text) . '!';
}
 
try {
    echo shout(['hi']);
} catch (TypeError $e) {
    echo 'Wrong type';
}

Output:

Wrong type

Notes

With declare(strict_types=1) the error is also raised when a number is passed instead of a string. Without it PHP tries to convert the value itself.

See also

  • Error — The base class of PHP's internal errors.
  • Throwable — The common interface of everything that can be thrown and caught.
  • InvalidArgumentException — The exception for an invalid function argument.

In the tutorial

  • The type system — Types in modern PHP — the strict_types mode, nullable and union types, void, never and typed properties.

Thanks for reading!

Donate to the site — we work hard for you.