Open In App

Explain type hinting in PHP

Last Updated : 10 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads