How to work with type declarations

Two functions that use type declarations

A function with one parameter type declaration

      function display_error(string $error) { 
        echo("<p class='error'>$error</p>\n");
      }
      

A function with type declarations for its parameters and return value

      function avg_of_3(int $x, int $y, int $z) : float {
        $avg = ($x + $y + $z) / 3;
        return $avg;
      }
      

Function calls without strict typing

      display_error('Value out of range.'); // Displays 'Value out of range.'
      display_error(1); // Displays '1'
      $average = avg_of_3(5, 2, 8); // $average is 5
      $average = avg_of_3(5.1, 2.7, 8.2); // $average is 5
      

How to enable strict types mode

      declare(strict_types=1);  // must be first line of script
      

Function calls with strict typing

      display_error('Value out of range.'); // Displays 'Value out of range.'
      display_error(1); // Fatal error
      $average = avg_of_3(5, 2, 8); // $average is 5
      $average = avg_of_3(5.1, 2.7, 8.2); // Fatal error
      

A typical error message when the data type isn’t correct

       TypeError: Argument 1 passed to avg_of_3() must be of the type integer, float given
      

Back