DEV Community

Md Jannatul Nayem
Md Jannatul Nayem

Posted on

Type Hinting in PHP function!

May be you know what is a function and how it works. PHP checks the data type at run time. Therefore we don't need to tell php explicitly the data type of a variable. PHP interpreter can detect it automatically. It has both advantage and disadvantage. Advantage is we don't need to think so much when declaring the variable but the problem is if the varaible is changed accidentally then it is very tough to debug.

But from php 7 it supports type hinting in function parameter. Support you want to print age of a user. Here is an approach.

<?php
function print_age($age){
    echo "your age is $age\n";
}
print_age(19);
Enter fullscreen mode Exit fullscreen mode

It is giving result perfectly. But what happens if you call it with a string. such as print_age("abc"); It will give some wrong output. Right? Here is the solution.

<?php
function print_age(int $age){
    echo "your age is $age\n";
}
print_age(19);
print_age("zig zag bla bla");
Enter fullscreen mode Exit fullscreen mode

Now you will get an fatal error for last line. It will enforce you to pass right parameter type. It can help us to find problem at early stage. Type hinting is possible for all php predefined data types.

Top comments (0)