Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Return Type Declarations

PHP 7 also supports type declarations for the return statement. Similar to type declarations for function arguments, enabling strict mode will result in a “Fatal Error” if there is a type mismatch.

To declare a return type for the function, add a colon (🙂 followed by the type just before the opening curly brace ({) when defining the function.

In the following example, we specify the return type for the function:

Example

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
  return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

You can specify a return type that differs from the argument types, but ensure that the return value is of the correct type.

Example

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
  return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);