Req #81177 [Com]: Typehint parameter is ignored when passing NULL directly. Is it correct?
Edit report at https://bugs.php.net/bug.php?id=81177&edit=1
ID: 81177
Comment by: rtrtrtrtrt at dfdfdfdf dot dfd
Reported by: 6562680 at gmail dot com
Summary: Typehint parameter is ignored when passing NULL
directly. Is it correct?
Status: Open
Type: Feature/Change Request
Package: Filter related
Operating System: Win10
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
> 1) If use just "$a" - it will fail is i didnt pass the argument
correct - it isn't an optional param
> 2) If use "int $a" - it will fail if argument is not an integer
correct
> 3) If use "$a = 123" - if wont fail and if i DIDNT PASS
> argument - it will be 123, but i still can pass NULL
what else? it's an optional, NON-TYPED param
so WHAT is your problem?
Previous Comments:
------------------------------------------------------------------------
[2021-06-19 18:51:55] 6562680 at gmail dot com
There is one problem with "section 2" way - PHPStorm wont highlight the function has
"default value"
------------------------------------------------------------------------
[2021-06-19 18:49:43] 6562680 at gmail dot com
Description:
------------
Usually it happens when another function pass its result to current, and it causes script to work
another way than request.
1) If use just "$a" - it will fail is i didnt pass the argument
2) If use "int $a" - it will fail if argument is not an integer
3) If use "$a = 123" - if wont fail and if i DIDNT PASS argument - it will be 123, but i
still can pass NULL and no fail there - seems correct, but logically NULL = undefined there.
4) If i use typehint "int $a = 123" - it will throw error if i pass NULL... What, i want
123 if i pass the null.
5) Ask my devs to ensure strict_types and rewrite all the project. Or just believe that
"speakers" (they aren't coders i think) who just cry "use everywhere
strict_types", and then solve that damn question marks in types...
For string its more complicated - empty string is string too...
Thank god we havent one more type = "undefined", in my 10 years practice that stuff was
needed maybe... 2-3 times for functions that could return anything/mixed.
There's not only manual code, some variable could contain NULL too.
Currently i solve it like "section 2" in script textarea below. It allows
"undefined" means - passed NULL or undefined, and controls integers. So on
Once i had just heared "You should use Classes instead of primitives all the time" and
"strong-typed languages better than your php", i dont want to believe, but seems i
should...
Test script:
---------------
// section 1
function hello($a = 123) {
var_dump($a); // NULL
}
$a = null;
hello($a);
// section 2
function hello(int $a = null) {
$a = $a ?? 123;
var_dump($a); // 123
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81177&edit=1
Thread (9 messages)