The order quantity from a form (the input boxes on a web page) reaches the server as the text "2", not the number 2. PHP usually turns it into a number without telling you, and the total on the receipt is still right. Then one day "two" arrives, and the cash register program stops with an error halfway through. It's safer to write the rule "only numbers go in" plainly from the start.
In modern PHP, that rule is written right on a function (a named block of code you can run again and again): which type may go in, and which type comes out. Picture Mrs. Tini's cash drawer. It has a box for paper money, a box for coins and a box for receipts, each one labelled. If someone drops a receipt in the money box, Mrs. Tini refuses it right away, before the count goes wrong. In code, each box is one place where a value goes into a function. The labels on the boxes become type declarations: the type written for each place. Only a value of that type may go in. Mrs. Tini refusing the receipt is a TypeError, the error that appears when a value of the wrong type goes in.
Functions with types
The Functions lesson covers functions in full later. Here the basic shape is enough:
<?php
function totalPrice(int $price, int $quantity): int
{
return $price * $quantity;
}
echo totalPrice(15, 2);
30
function totalPrice(...)creates a function namedtotalPrice. Its code goes between{and}.int $price, int $quantityare parameters, the variables that receive the values when the function is called (run). Theintin front of each one is the type allowed in.: intafter the brackets is the return type, the type of the value that comes out.returnsends the result of$price * $quantityout of the function, to the place where the function was called.totalPrice(15, 2)calls the function:$pricebecomes 15,$quantitybecomes 2. The values you send when you call it, here 15 and 2, are called arguments.
When the type doesn't fit
Form input is always a string, so $quantity often arrives as "2". The table shows the result of totalPrice(15, ...) for each second argument. The last column uses strict_types, a setting covered in the next section.
| Second argument | Without strict_types | With strict_types |
|---|---|---|
2 |
30 |
30 |
"2" |
30, "2" turned into 2 |
TypeError, string given |
"two" |
TypeError, string given | TypeError, string given |
2.5 |
30 plus a Deprecated |
TypeError, float given |
null |
TypeError, null given | TypeError, null given |
Deprecated is a warning: this still works, but a later version of PHP may not support it. Here 2.5 is cut to 2.
With no setting at all, PHP uses coercive mode (a mode that changes the type when it can): a string that holds a number is turned into a number. "two" can't be turned into a number, so PHP stops:
Fatal error: Uncaught TypeError: totalPrice(): Argument #2 ($quantity) must be of type int, string given, called in /app/till.php on line 8 and defined in /app/till.php:3
Read the message from the left: the function totalPrice(), argument 2 ($quantity), should be int, a string came in, called on line 8, the function is written on line 3.
strict_types: no more guessing
This is the same code, with one new line below <?php, and "2" as the second argument:
<?php
declare(strict_types=1);
function totalPrice(int $price, int $quantity): int
{
return $price * $quantity;
}
echo totalPrice(15, "2");
Fatal error: Uncaught TypeError: totalPrice(): Argument #2 ($quantity) must be of type int, string given, called in /app/till.php on line 9 and defined in /app/till.php:4
declare(strict_types=1);turns off automatic type changes for the functions called in that file. Only an int may go into anintparameter.- Without this line,
totalPrice(15, "2")prints30. With it, the result is a TypeError. - One exception: an int may still go into a
floatparameter. - This line must be the first statement after
<?php. If any statement is above it, PHP stops withFatal error: strict_types declaration must be the very first statement in the script.
Nullable ? and union |
Mrs. Tini's cash register program looks up a price by menu code. The menu code can be a number (1) or text ("iced-tea"), and sometimes the menu code isn't found:
<?php
function menuPrice(int|string $code): ?int
{
$prices = [
1 => 15,
"iced-tea" => 5,
];
if (isset($prices[$code])) {
return $prices[$code];
}
return null;
}
var_dump(menuPrice(1));
var_dump(menuPrice("iced-tea"));
var_dump(menuPrice(99));
int(15)
int(5)
NULL
int|stringis a union type (available since PHP 8.0): the parameter takes an int or a string.?intis a nullable type: the result is an int, ornullwhen the code isn't found.?intis the same asint|null.$pricesis an array (one variable that holds many values) with keys: the key left of=>points to the value on its right.$prices[$code]reads the value with the key$code. The Array lesson covers it in full.isset($prices[$code])answerstruewhen that key exists.if (...) { ... }runs the code between{and}only when the condition in the brackets istrue.- Code 99 isn't there, so the function reaches
return null. If you forget that line, PHP refuses:menuPrice(): Return value must be of type ?int, none returned. echowrites nothing for null. To check for null, usevar_dump, orvar_export(menuPrice(99) === null);, which writestrue(not1asecho truedoes).===means exactly the same, covered in the next section.
== and ===
PHP has two ways to compare two values. The comment on each line is the result:
var_dump("15" == 15); // bool(true)
var_dump("15" === 15); // bool(false)
var_dump(0 == "a"); // bool(false)
var_dump("1" == "01"); // bool(true)
==makes the types match first, then compares.===compares the value and also the type: a string compared with an int isfalseright away.- PHP 8 changed the rule for a number compared with text:
0 == "a"is nowfalse(in PHP 7 it wastrue). - Two strings that hold numbers are still compared as numbers, so
"1" == "01"istrue. Make===your habit.
Form input: check first, then convert. With strict_types, the input "2" has to become an int before it goes into totalPrice. (int) in front of a value forces it into an int. Don't just use (int), because it hides wrong input. filter_var($input, FILTER_VALIDATE_INT) is safer: it gives an int when the input is a whole number, and false when it isn't.
var_dump((int) "two"); // int(0), no error
var_dump((int) "2abc"); // int(2)
var_dump(filter_var("2", FILTER_VALIDATE_INT)); // int(2)
var_dump(filter_var("2abc", FILTER_VALIDATE_INT)); // bool(false)
$quantity = filter_var("two", FILTER_VALIDATE_INT);
if ($quantity === false) {
echo "The quantity must be a whole number.";
} else {
echo totalPrice(15, $quantity);
}
(int) "two" becomes 0 without any warning, so the receipt could print a total of 0. For "two", filter_var answers false. So the condition $quantity === false is true, the if writes a message, and the else part (which runs when the condition is false) is skipped. So totalPrice is never called. After the four var_dump lines, the code above writes The quantity must be a whole number. The Form Handling lesson uses filter_var again for form input.
📌 Other types you'll meet
void: the function does notreturnany value, for example it only prints a receipt.mixed: any type is allowed. Avoid it when the real type can be written.never: the function never finishes normally. It always ends with an error or by stopping the program.- Intersection types (
A&B) andreadonlyproperties are used with classes, which the OOP lessons cover.
⚠️ The first line, form input, and the forgotten null
declareisn't the first line. Putdeclare(strict_types=1);right after<?php, before any other statement.- Form input sent as it is. With strict_types, the string
"2"is refused. Check and convert it first withfilter_var, then handle afalseresult. Use(int) "2"only for a value you have already checked, because(int) "two"becomes0without any warning. - Nullable without
return null.?intallows null, but you still have to write the null in areturn. - Checking null with echo.
echo nullwrites nothing, so it looks the same as an empty string. Use=== null.
TL;DR: Types are written on the function (a named block of code). In function totalPrice(int $price, int $quantity): int, the int in front of each parameter (a variable that receives a value) is the type allowed in, and : int is the type that comes out. With no setting, PHP turns "2" into 2, but refuses "two" and null with a TypeError (an error for a value of the wrong type). declare(strict_types=1); on the first line lets only an int in. ?int means an int or null (? = nullable), int|string means either one (| = union). A function with ?int still has to write return null, and null is checked with === null (exactly the same as null), not echo. == makes the types match first ("15" == 15 is true), === compares the value and the type, so make === your habit.
⚡ Types are written on the function
Write:
<?php
function totalPrice(int $price, int $quantity): int
{
return $price * $quantity;
}
echo totalPrice(15, 2);
Meaning: A function is a named block of code you can call (run) again and again. The int in front of each parameter (a variable that receives a value) is the type allowed in, and : int after the brackets is the type of the value that comes out through return. The result is 30. If "two" goes in, PHP stops with a TypeError (an error for a value of the wrong type).
⚡ strict_types: no more guessing
Guess first: what does totalPrice(15, "2") give?
With no setting at all, 30: PHP turns "2" into 2. With declare(strict_types=1); on the first line, a TypeError.
Meaning: declare(strict_types=1); lets only an int into an int parameter. Write this line right after <?php, before any other statement.
⚡ ? allows null, | means either one
Write:
function menuPrice(int|string $code): ?int
Meaning: int|string means the parameter takes an int or a string (a union type). ?int means the result is an int or null (nullable). A function with ?int still has to write return null itself. Check for null with === null (exactly the same), not with echo, because echo null writes nothing.