PHP Type Declarations
Type declarations name the types that a function works with. A typed parameter names its type before the parameter name.
Typed parameters
The word int sits before each parameter. Both arguments are ints, and the sum prints.
<?php
function add(int $a, int $b) {
return $a + $b;
}
echo add(4, 3) . "\n";A numeric string converts
The default mode converts a numeric string for an int parameter. The text 5 becomes the number 5, so the sum is 8.
<?php
function add(int $a, int $b) {
return $a + $b;
}
echo add("5", 3) . "\n";A return type
A return type now sits after the parameter list. The colon and the word int name the type of the value sent back.
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add(4, 3) . "\n";Text that cannot convert
The text abc cannot become an int. The program stops with this error line.
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add("abc", 3) . "\n";Example
<?php
function total(float $price, int $count): float {
return $price * $count;
}
echo total(2.5, 3) . "\n";Key points
- A typed parameter accepts values of its named type.
- PHP converts a numeric string to a number for a typed parameter in the default mode.
- A text value that is not numeric cannot convert to an int.
- A return type is written after the parameter list, behind a colon.
- PHP checks the value a function sends back against its return type.
In this example, total takes a float price and an int count. It sends back their product as a float. The call passes 2.5 and 3, and the program prints 7.5.
Note
A file can ask for strict checks with declare(strict_types=1) instead of the default mode.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
What happens when a call passes the text abc to a parameter typed int?