Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do strict types in PHP affect variables?

Tags:

php

php-7

I know when using declare(strict_types=1) I must pass parameters of given type otherwise an Exception is raised, but one question:

declare(strict_types=1);

function add(int $firstNumber, int $secondNumber)
{
    $firstNumber = "example";

    return $firstNumber . " " . $secondNumber;
}

My question is why I'm allowed to change the $firstNumber's type to string if int was declared?

For instance, in Java, I can't do casting that way. Parameter type int must remain int otherwise code won't even compile.

like image 603
AdrianeZ - programuj Avatar asked Oct 27 '25 10:10

AdrianeZ - programuj


1 Answers

It is because you are strict typing only the input of the function, not the return or any of the variables in the function itself. From the docs -

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared...

So your call to the function with a non-integer:

add('example',2);

will return the error you expect -

Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, string given, called in...

But sending integers to your function will allow the function call to proceed and variables within will be weakly typed.

like image 86
Jay Blanchard Avatar answered Oct 29 '25 00:10

Jay Blanchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!