I'd have expected the following to generate a type error as 123
is an integer and not a string, so is it okay to provide an integer to a function that expects a string?
foo(123);
function foo(string $str) {
...
}
I'd have expected the following to generate a type error as 123
is an integer and not a string, so is it okay to provide an integer to a function that expects a string?
foo(123);
function foo(string $str) {
...
}
Yes, because an integer can be converted to string (an array cannot for example).
Yes, unless you declare declare(strict_types=1)
.
foo(123);
function foo(string $str) {
var_dump($str); // string(3) "123"
}
But the following:
declare(strict_types=1);
function foo(string $str) { }
foo(123); // FAIL (Uncaught TypeError)
Will throw:
Fatal error: Uncaught TypeError: foo(): Argument #1 ($str) must be of type string, int given
The PHP manual is pretty specific about this behavior, and speaks directly to the example you posed:
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
Whether this is "OK" or not (as you asked) is highly implementation-dependent.