Just discovered that type-hinting is allowed in PHP, but not for ints, strings, bools, or floats.
Why does PHP not allow type hinting for types like integer, strings, ... ?
As of PHP 7.0 there is support for bool
, int
, float
and string
. Support was added in the scalar types RFC. There are two modes: weak and strict. I recommend reading the RFC to fully understand the differences, but essentially type conversions only happen in weak mode.
Given this code:
function mul2(int $x) {
return $x * 2;
}
mul2("1");
Under weak mode (which is the default mode) this will convert "1"
to 1
.
To enable strict types add declare(strict_types=1);
to the top of the file. Under strict mode an error will be emitted:
Fatal error: Argument 1 passed to mul2() must be of the type integer, string given
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With