Strict types

Type declarations name the values a function accepts and returns. In PHP the engine checks them at the call, and one statement at the top of the file decides whether a close value is converted or refused.

declare(strict_types=1)

By default PHP coerces scalar arguments, so a string with digits can slip into an int parameter. One declare at the top of the file switches that file to exact checks.

It must be the first statement in the file, before any other code or output.

<?php declare(strict_types=1); function doubleInt(int $n): int { return $n * 2; } echo doubleInt(21), PHP_EOL;

php declare.php

42

The integer argument matches the declaration and the integer return matches the caller. The same file with the string "21" would stop before the body ran.

Scalar declarations

Declare int, float, string, and bool for every scalar input. Readers see the contract at once, and the engine rejects wrong types early.

In strict mode passing a numeric string to an int parameter throws a TypeError.

<?php declare(strict_types=1); function greet(string $name, int $age): string { return $name; } echo greet("Ada", 36), PHP_EOL; try { echo greet("Ada", "36"), PHP_EOL; } catch (TypeError $e) { echo get_class($e), PHP_EOL; }

php scalar.php

Ada
TypeError

The first call satisfies both parameters, and the second one stops at the string where an int is declared. The catch proves that the refusal is a TypeError and not a warning.

Return types

A return type guarantees what the caller receives. Add it after a colon behind the parameter list. void means nothing is returned, which keeps command style functions honest.

Mismatched returns fail fast instead of leaking bad data downstream.

<?php function loadIds(): array { return [1, 2, 3]; } function logLine(string $line): void { echo $line, PHP_EOL; } echo implode(",", loadIds()), PHP_EOL; logLine("logged");

php return.php

1,2,3
logged

The ids are joined with implode() into one line, and the void function prints its own line without returning a value. A function declared void that writes return 5; is a fatal error at compile time.

Union

When a value can legitimately be one of several types, list them with a vertical bar. This is clearer than leaving the parameter untyped.

Keep unions short. Long lists often signal that the function does too much.

<?php function toNumber(int|float $value): int|float { return $value; } var_dump(toNumber(5)); var_dump(toNumber(5.5));

php union.php

int(5)
float(5.5)

Each call keeps the type it was given, because the union allows both and the function returns it unchanged. The dump shows the type, which an echo would hide.

nullable and never

A question mark marks a type as nullable, so null joins the allowed set. Use it for optional results like a missing record.

The never return type marks functions that never return at all because they always throw or exit. It documents terminal paths for readers and static analyzers.

<?php function findName(int $id): ?string { if ($id < 1) { return null; } return "Ada"; } function abort(string $msg): never { throw new RuntimeException($msg); } var_dump(findName(0)); echo findName(5), PHP_EOL; try { abort("stop"); } catch (RuntimeException $e) { echo $e->getMessage(), PHP_EOL; }

php nullable.php

NULL
Ada
stop

The missing id answers with null and the found one with the name, both allowed by the question mark. The never function cannot return at all, so the message it throws is the only way out.

Exercises

  1. Change doubleInt(21) to doubleInt("21") in declare.php and run it. What does PHP print?
  2. Remove the declare line from scalar.php and run it again. Does the second call still fail?
  3. Give loadIds() a ?array return type and make it return null when the list is empty.
  4. Add a bool parameter to greet() and pass the number 1 from a strict file.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does declare(strict_types=1) change?

    Answer

    Scalar arguments and returns are checked exactly, without coercion

    Strict mode removes the conversion of close values, so a string is not accepted where an int is declared.

  2. Where must the strict declare sit?

    Answer

    As the first statement of the file

    PHP reads the directive before it compiles the rest, so it comes first, before any output.

  3. What does the void return type mean?

    Answer

    The function returns nothing

    A void function runs for its side effect and has no value for the caller.

  4. What does the never return type mean?

    Answer

    The function always throws or exits and never returns

    The compiler checks that every path of a never function ends in a throw or an exit.

  5. What does this program print? <?php declare(strict_types=1); function doubleInt(int $n): int { return $n * 2; } echo doubleInt(21);

    Answer

    42

    The integer argument matches the declaration and the body doubles it.

  6. What does this program print? <?php declare(strict_types=1); function greet(string $name, int $age): string { return $name; } try { echo greet("Ada", "36"); } catch (TypeError $e) { echo get_class($e); }

    Answer

    TypeError

    In a strict file the numeric string is not converted to an int, so the call throws a TypeError.

  7. What does this program print? <?php function toNumber(int|float $value): int|float { return $value; } var_dump(toNumber(5)); var_dump(toNumber(5.5));

    Answer

    int(5) / float(5.5)

    The union accepts both types and the function returns each argument with the type it came in.

  8. What does this program print? <?php function findName(int $id): ?string { if ($id < 1) { return null; } return "Ada"; } var_dump(findName(0));

    Answer

    NULL

    The zero takes the early return, and the question mark allows the null.

  9. What does this program print? <?php function abort(string $msg): never { throw new RuntimeException($msg); } try { abort("stop"); } catch (RuntimeException $e) { echo $e->getMessage(); }

    Answer

    stop

    The never function can only throw, and the catch prints the message it carried.

  10. A file without the strict declare calls doubleInt(int $n) with the string "5". What does the program print? <?php function doubleInt(int $n): int { return $n * 2; } echo doubleInt("5");

    Answer

    10

    Without strict types PHP converts the numeric string to an int, so the call succeeds.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev