Reputation: 263
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.
Upvotes: 4
Views: 956
Reputation: 34426
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.
Upvotes: 3