0
function addition(int $number1, int $number2): int
{
    return $number1 + $number2;
}

print('<pre>');
print_r(addition(2, "10"));
print('</pre>');

As a result of above code, it gives me 12. But it should give me an error. Because the second parameter should be an int. But I passed string. Can anyone tell me what kind of behavior happen here?

Thanks in advance.

Hemantha Dhanushka
  • 153
  • 1
  • 5
  • 14
  • My guess is that it gets typecast to an integer, as `"10" == 10`. The problem arise when you say `addition(2,'3x)` – Qirel Jul 17 '19 at 10:18

3 Answers3

4

Declare strict_types(). By default, it is scalar type which is not strict. Also strict_types() has more control over your codes.

declare(strict_types=1);

function addition(int $number1, int $number2): int
{
    return $number1 + $number2;
}
MH2K9
  • 11,951
  • 7
  • 32
  • 49
1

IF you are using PHP7, add this:

declare(strict_types = 1);

at the very first line of the script, and than you will get an error. enter image description here

JureW
  • 641
  • 1
  • 6
  • 15
0

PHP is loosely typed scripting language and there is no restriction on the variables type and their nature.

$i = "10";

will be considered both integer and the string.

you can read more about this nature by searching about "Why PHP is loosely typed?"

  • 1
    Can you explain further what you mean by "considered both integer and the string"? As far as I see, that is definitely a string that might get casted, but it cannot be both at the same time – Nico Haase Jul 17 '19 at 10:40