| Subject | Details |
| :------------- | :---------------------------------------------------------------------------- |
| Plugin | Php Inspections (EA Extended) or Php Inspections (EA Ultimate), 3.0.10 |
| Language level | PHP 8 |
For the following code
<?php
class Foo {
public function returnBool(): bool {
return random_int(0,1) > 0;
}
}
function returnsBool(?Foo $foo): bool {
return (bool) $foo?->returnBool();
}
var_dump(returnsBool(null));
(bool) is highlighted as unnecessary type cast.
As it can be seen here, when there is no type cast, a TypeError is thrown.
n/a
How does the TypeError which is clearly intended in the code example by specifying the return type bool render the type casting necessary?
You either have the wrong return type or the return code is written "wrong". In both cases the cast is indeed unnecessary:
return $foo?->returnBool() ?? false;
you want to have null in the null safe operation as false - express it ;) - as it can be seen here.
Thanks for reporting @canvural, we are able to reproduce the bug. We are working on fixing it.
@ktomk: the reported construct is fully valid, and following inspection suggestion will change behavior. Different projects have different coding standards, so the suggested alternative might not fit to what folks are doing on daily basis. We need to fix this on our end.
@ea-inspections-team: I'm in for the tweak.
Fixed! The fix will be available in the next release.
Most helpful comment
@ktomk: the reported construct is fully valid, and following inspection suggestion will change behavior. Different projects have different coding standards, so the suggested alternative might not fit to what folks are doing on daily basis. We need to fix this on our end.