Re: [Discussion] Stricter implicit boolean coercions
| From: | Craig Francis | Date: | Mon, 23 May 2022 19:38:26 +0000 |
| Subject: | Re: [Discussion] Stricter implicit boolean coercions | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-117775@lists.php.net to get a copy of this message | ||
On 23 May 2022, at 19:58, Juliette Reinders Folmer <php-internals_nospam@adviesenzo.nl> wrote:
> I also fear that for code bases which do not (yet) use scalar type declarations, this will be
> one more argument not to introduce scalar type declarations (while they should).
>
> I'd say that for this RFC to be acceptable it would need to apply to all implicit type
> coercions to boolean. However, the BC-break that would cause and the fall-out of this for
> non-greenfields codebases is just too huge, which, to me, makes this RFC a very strong no-no.
Forgive my ignorance, but when scalar types were introduced, I initially assumed type coercion would
use the same rules as
strval($var), (string) $val, 'a' .
$val, intval($val), etc. I now appreciate that isn't the case, but I never
understood why the following functions were not equivalent:
```
function my_function1($s, $i, $f, $b) {
$s = strval($s);
$i = intval($i);
$f = floatval($f);
$b = boolval($b);
var_dump($s, $i, $f, $b);
}
function my_function2(string $s, int $i, float $f, bool $b) {
var_dump($s, $i, $f, $b);
}
```
Where the second function, using scalar type declarations, has the advantage of being much shorter,
and clearer for Static Analysis, IDE's, documentation, etc... if only it was as easy to add to
existing projects.
This isn't to say boolval() and other ways of changing type to a boolean
couldn't throw a type error with unrecognised strings (e.g. "false"), and doing so
might make sense (although I do share Juliette's concerns about the BC-breaks).
Craig