Thursday, September 4, 2025
HomeLanguagesExplain type hinting in PHP

Explain type hinting in PHP

Type hinting is a concept that provides hints to function for the expected data type of arguments.

For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter. While calling the function we need to provide an argument of integer type only. If you provide data of any other type, it will throw an error with clear instructions that the value of an integer type is needed.

Advantages of type hinting:

  • Type hinting helps users debug the code easily or the code provides errors very specifically.
  • It is a great concept for static kind of programming/data.

Disadvantages of type hinting:

  • Functions only take one type of data.
  • The dynamicity of data or argument is not there.

Example 1: In the following example, $var1 of type “cls” class is passed to the display() function. It displays the text of the class “cls”.

PHP




<?php
  
  class cls{
      public $sentence="Hi welcome to php world";
  }
  
  function display(cls $var1){
      echo $var1->sentence;
  }
  
  display(new cls());
?>


Output:

Hi welcome to php world

Example 2: The following example shows that $numbers is passed as a parameter to the add() function which is of type array. All the array items are added using the PHP foreach() loop.

PHP




<?php
  
  function add(array $numbers){
      $sum=0;
      foreach($numbers as $item){
          $sum=$sum+$item;
      }
      echo $sum;
  }
  
  add(array(10,10));
?>


Output:

20

If an integer is passed, the following error is thrown.

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6632 POSTS0 COMMENTS
Nicole Veronica
11800 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11859 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS