Should we use type hints

Type notes with declare strict

Switch to strict mode

PHP works by default in the so-called. non-scrict-mode. In this mode it is not possible to explicitly specify the data type when defining variables. PHP determines the data type from the context.

Let's look at an example:

Depending on the assigned value (string, integer, ...) the variables $ var1 and $ var2 "automatically" receive the appropriate data type, as we were able to prove with gettype.

The problem

It is often practical that the data type is not declared for variables. At Functions can be a problem become. Let's look at a simple example:

This function should add two numbers together and return the result. This works as expected with the following function call:

So far so good. But what happens if we pass two strings, let's say "1" and "2", to the function?

Perhaps a bit surprising that this also succeeds and results in 3 (data type: integer). The reason is that PHP treats the two strings here as numbers.

Even the following function call is not a problem:

And that is really going too far!

The solution: type notes

To ensure that only explicitly declared data types are valid when the function is called, since PHP 7 there has been the option of entering the strict mode to switch and with it Type information (typehints) to use.

To do this, a very specific instruction must first be included at the top of the PHP files:

We are now in scrict mode and can set type notes. These type notes are possible for the parameter and Return types of functions. We'll see exactly how this works in the next few steps.