Open In App

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:

Disadvantages of type hinting:



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
  
  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
  
  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.


Article Tags :