How to Declare Parameter and Return Types in PHP Functions

Quick Summary
- Since PHP 7, declare scalar types such as int and string on function parameters and add a return type after the parentheses.
- In the default coercive mode PHP converts safe values, so the string 5 becomes an integer, while a string like five throws a TypeError.
- Add declare(strict_types=1); as the first statement of a file to stop conversion, but it only affects calls made from that file.
Since PHP 7 you can add parameter and return type declarations to functions: scalar types such as int and string for the parameters, and the type the function returns. The declarations make a function’s contract explicit: when a value of the wrong kind goes in or comes out, PHP either converts it, if it safely can, or throws a TypeError instead of carrying on with bad data.
<?php
//INT TYPE
function sum(int $x, int $y, int $z):int {
return $x+$y+$z;
}
echo sum(5,5,5);
//STRING TYPE
function txt( string $fname, string $lname):string {
return $fname.' '.$lname;
}
echo txt('Sherlock','Holmes');?>How it works
int $x, int $y, int $zsays each parameter must be an integer. The:intafter the parentheses is the return type, sosum()must return an integer.sum(5,5,5)prints 15.txt()takes two strings and returns a string: the first name, a space and the last name. It prints Sherlock Holmes.- By default PHP runs in coercive mode.
sum( "5", 5, 5 )still works because the string"5"is converted to the integer 5, butsum( "five", 5, 5 )throws aTypeError.
Strict mode
To stop PHP from converting values, add declare(strict_types=1); as the very first statement of the file. From then on, calls made from that file must pass real integers to int parameters and real strings to string parameters, or PHP throws a TypeError. The setting affects that file only, not your whole project.
The same syntax works with other types such as float, bool, array and class names, so you can use it to catch mistakes early in your own functions. It also works with variadic parameters, as in int ...$numbers, and with parameters that have a default value.
Related articles
- the data types available in PHP: the types you can declare

