PHP ยท Chapter 19 of 44

PHP Return Types & Type Declarations

PHP allows you to declare the expected types of function parameters and return values, which is called type hinting or type declarations. This helps catch bugs early and makes your code's intent clearer.

You can specify types like int, float, string, bool, array, or a class name for parameters, and add a return type after the parameter list using a colon. PHP will throw a TypeError if the wrong type is passed in strict mode.

Syntax
function add(int $a, int $b): int {
  return $a + $b;
}

Parameter type declarations

Adding a type before a parameter name, like function setAge(int $age), tells PHP (and other developers) exactly what type is expected.

Return type declarations

A colon followed by a type after the parameter list, like function add(int $a, int $b): int, declares what type the function will return.

Example 1 (php)
<?php
  function add(int $a, int $b): int {
    return $a + $b;
  }
  echo add(2, 3);
?>
Output
5

Both parameters and the return value are declared as int, making the contract clear.

Example 2 (php)
<?php
  function greet(string $name): string {
    return "Hi, $name";
  }
  echo greet("Amy");
?>
Output
Hi, Amy

The function only accepts a string and promises to return a string.

Key points

  • Type declarations specify expected types for parameters and return values.
  • A colon before the function body declares the return type.
  • declare(strict_types=1); enforces strict type checking.
  • Type declarations make code easier to understand and debug.
๐Ÿ’ก Note: Add declare(strict_types=1); at the top of a file to prevent PHP from silently converting types.

๐Ÿ“ Quick Quiz

1. How is a return type declared in PHP?

2. What does declare(strict_types=1); do?

3. What error is thrown when the wrong type is passed with strict types on?