0

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) {
    ...
}
nick
  • 3,544
  • 1
  • 26
  • 22
  • 1
    Also note that strict type declaration doesn't make PHP strictly typed. PHP is still loosely typed. Its just the function/method params and return values that are type checked. See demo: http://sandbox.onlinephpfunctions.com/code/0867aa978a85fd0b76079c31215745831e03137c – nice_dev Apr 02 '21 at 18:46
  • 1
    Very informative thanks! – nick Apr 02 '21 at 18:48

2 Answers2

3

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

Syscall
  • 19,327
  • 10
  • 37
  • 52
2

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.

esqew
  • 42,425
  • 27
  • 92
  • 132