PHP type hinting: bool and int -
i debugged php 7.1 code in wp plugin function returning 0
or 1
when expected various other ints. realized i'd forgotten remove (bool)
cast earlier.
but made me wonder, because function had return type of int
. here's simplified version:
function get_foo(): int { $val = get_option('foo'); // returns string can parsed int return (bool) $val; } $foo = get_foo();
it's easy cast between bool
, int
, of course, why didn't throw typeerror?
there 3 scenarios typeerror may thrown. ... second value being returned function not match declared function return type.
you need add strict_types
directive type hinting work properly
quoting php 7 new features
to enable strict mode, single declare directive must placed @ top of file. means strictness of typing scalars configured on per-file basis. directive not affects type declarations of parameters, function's return type (see return type declarations, built-in php functions, , functions loaded extensions.
with that, should this.
<?php declare(strict_types=1); function get_option_foo() : int { $val = get_option('foo'); // returns string can parsed int return (bool) $val; } $foo = get_option_foo();
try once again, receive uncaught typeerror exception
Comments
Post a Comment