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 typeNotes
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.