What is php type hinting?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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

    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

    Output:

    20

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


    Summary: in this tutorial, you’ll learn how to use PHP type hints to declare the types for function parameters and return values.

    Introduction to PHP type hints

    PHP is a dynamically typed language. When you define a function, you don’t need to declare types for parameters. For example:

    Chủ Đề