DEV Community

Md Jannatul Nayem
Md Jannatul Nayem

Posted on

2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs