- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<?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
<?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
<?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