PHP TypeError


Introduction

TypeError class extends Error class. This error is raised when actual and formal argument types don't match, return type doesn't match the decalred returned type or invalid arguments passed to any built-in function

Note that strict_types should be set to true with declare() function at the top of script −

In this example, types of formal and actual argument variables don't match, resulting in TypeError.

Example

 Live Demo

<?php
function add(int $first, int $second){
   echo "addition: " . $first + second;
}
try {
   add('first', 'second');
}
catch (TypeError $e) {
   echo $e->getMessage(), "
"; } ?>

This will produce following result −

Output

Argument 1 passed to add() must be of the type integer, string given, called in C:\xampp\php\test.php on line 9

In following example, user defined function is supposed to return integer data, instead it is returning an array, which causes TypeError

Example

 Live Demo

<?php
function myfunction(int $first, int $second): int{
   return array($first,$second);
}
try {
   $val=myfunction(10, 20);
   echo "returned data : ". $val;
}
catch (TypeError $e) {
   echo $e->getMessage(), "
"; } ?>

Output

This will produce following result −

Return value of myfunction() must be of the type integer, array returned

TypeError is also thrown when PHP's built-in function is passed incorrect number of arguments. However, strict_types=1 directive must be set in the beginning

Example

 Live Demo

<?php
declare(strict_types=1);
try{
   echo pow(100,2,3);
}
catch (TypeError $e) {
   echo $e->getMessage(), "
"; } ?>

Output

This will produce following result −

pow() expects exactly 2 parameters, 3 given

Updated on: 21-Sep-2020

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements