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(); 

test code here.

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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -