declare(strict_types=1) and Type Juggling
Lesson 5 of 43 in the PHP 8 learning path.
How do I stop PHP from silently coercing function arguments?
declare(strict_types=1) is a per-file switch for scalar type checks. It has to be the first statement. It changes calls that appear in that file, and it does not travel with a function into other files. If this file calls seatLabel(24, "web"), the int and the string match the parameters and the call succeeds. If this same file calls seatLabel("24", "web"), PHP throws a TypeError instead of turning the string into an int. A second file that omits the directive can still call seatLabel("24", "web") and the engine will coerce, because the caller file decides the argument mode.
Return checks use the file that contains the return statement, which is the file that defined the function. Calls you make to internal functions such as strlen() are strict when they appear in this file, so strlen(24) throws. Calls that array_map makes into your callback stay coercive, and == still coerces.
Syntax & Parameters
declare(strict_types=1);
function seatLabel(int $seats, string $track): string
Example
<?php
declare(strict_types=1);
function seatLabel(int $seats, string $track): string
{
$noun = $seats === 1 ? 'seat' : 'seats';
return $seats . ' ' . $noun . ' on ' . $track;
}
function asSeatCount(int $seats): int
{
return $seats;
}
function typeErrorText(TypeError $error): string
{
$message = $error->getMessage();
$cut = strpos($message, ', called in ');
return $cut === false ? $message : substr($message, 0, $cut);
}
echo 'label=' . seatLabel(24, 'web') . "\n";
try {
seatLabel('24', 'web');
echo "direct=accepted\n";
} catch (TypeError $error) {
echo 'direct=' . typeErrorText($error) . "\n";
}
try {
strlen(24);
echo "internal=accepted\n";
} catch (TypeError $error) {
echo 'internal=' . typeErrorText($error) . "\n";
}
// array_map performs this call from internal code, which stays coercive.
$mapped = array_map(asSeatCount(...), ['1', '2']);
echo 'map=' . implode(',', $mapped) . "\n";
echo 'loose_equal=' . ((24 == '24') ? 'yes' : 'no') . "\n";
Expected Output
label=24 seats on web direct=seatLabel(): Argument #1 ($seats) must be of type int, string given internal=strlen(): Argument #1 ($string) must be of type string, int given map=1,2 loose_equal=yes
Line-by-Line Walkthrough
- declare(strict_types=1) is the first statement and applies only to this file, including every direct call written below it.
- seatLabel() declares an int seat count and a string track, then returns a string built from those values.
- seatLabel(24, "web") is a direct call in this strict file with matching types, so the label line prints 24 seats on web.
- seatLabel("24", "web") is also a direct call in this file, so PHP throws TypeError instead of casting the numeric string.
- typeErrorText() trims the path off the exception so the classroom output keeps the stable part of the message.
- strlen(24) is a call from this strict file to an internal function, and that call site is strict, so a TypeError is thrown.
- array_map() calls asSeatCount() from inside the engine, and internal call sites stay coercive, so the strings 1 and 2 become ints and map prints 1,2.
- A different file without the directive could call seatLabel("24", "web") and would still receive coercion, because the caller file chooses the argument mode.
- Return checks use the mode of the file that contains the return. seatLabel() returns a real string from this strict file, so its return check passes.
- 24 == "24" prints yes because strict_types does not change ==, ===, arithmetic, or other operators.
- Included files do not inherit the directive. Each file that wants strict calls declares it itself.
- An int may still be passed where a float is declared. That widening conversion remains legal in a strict file.
Common Pitfalls & Security
The common mistake is to treat strict_types as a project-wide freeze on coercion, or as a property of the function definition. It is a property of the file that contains the call for arguments, and of the file that contains the return for return values. A grade-book total that silently becomes an int in one entry point and throws in another is usually two files with two different directives.
- Putting the declare only in the file that defines seatLabel() leaves other callers in coercive mode. Add the directive to each caller file.
- array_map(), array_filter(), and similar internals call your callback weakly. A numeric string in that list can enter an int parameter without a TypeError.
- strlen(), substr(), and other internal functions with scalar parameters throw when a strict file passes the wrong type. That surprises code ported from PHP 7 tutorials that passed ints to strlen().
- == and + keep coercing. strict_types is the wrong tool for those operators. Use === and validate before arithmetic.
- An int still satisfies a float parameter. Passing 90 to a float average is legal and will not throw.
- Unsafe anti-pattern (do not ship): catching TypeError and then casting the bad input so the call "succeeds." Reject the request and show a validation message.
Best Practices & Modern Standards
Start every PHP 8.3 application file and every class file with declare(strict_types=1). Pair it with parameter and return types so a seat count that is still a string fails at the call, where the form parser can turn it into a validation error. Keep one small validation step at the HTTP boundary that converts request text into ints and strings before the rest of the code runs strict.
Do not expect the directive to rewrite operators or callbacks invoked by the engine. After array_map(), the values that enter a typed callback may already have been coerced. Normalize list data before the call when the element type matters, and test the direct call and the callback path separately.
Real-World Use
The enrollment form posts the string "24" for seats. The controller either rejects it or casts it with an explicit check, then calls seatLabel(24, "web") from a file that declares strict types. A second report script that forgets the directive would quietly accept the string. The grade book keeps the directive on every entry script so the section size cannot change type on the way into the roster.
Frequently Asked Questions
Does strict_types in the function file protect every caller?
No. Argument checks use the file that contains the call. A weak file can call a function that was defined in a strict file and PHP will still coerce scalar arguments. Put the directive in the caller.
Are return types checked with the caller mode or the defining file?
Return types are checked where the return statement runs, in the file that defined the function, using that file mode. A strict defining file rejects return "4" from a function declared to return int.
Why did array_map accept the strings "1" and "2"?
array_map() is an internal function. When it calls asSeatCount(), that call site is internal, and internal call sites are coercive even if your file declared strict_types. A direct call to asSeatCount("1") in this file would throw.
Does a strict file stop 24 == "24"?
No. The sample prints loose_equal=yes. Use === for a comparison that includes the type, and use strict_types for typed calls and returns.