Type Declarations

Last updated

What is Type Declarations?

Type declarations, also known as type hints, are a feature in PHP that provides you options to specify the type of variable that a function is expected to receive or the type of value that it should return. Not only does it help to debug code quickly, it also makes the code more readable. In PHP, type declarations can be for both parameters in a function (parameter type declarations) and return values from a function (return type declarations). They can apply to classes, interfaces, callable, and scalar types (int, float, string, bool).

Here's an example:

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(1, 2);  // prints: 3

In this example, the function 'add' only accepts integers and also returns an integer.

Free resources to learn Type Declarations

More in stage 12: PHP-FIG

Type Declarations: common questions

Can I learn Type Declarations in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Type Declarations in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Type Declarations tutorial for beginners?

It is lesson 90 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me