[php-src] Issue #20632: Use better error message for non-numeric strings in implicit contexts
[email protected] (IMSoP)
| Newsgroups | php.bugs |
|---|---|
| Message-ID | <E6NQQ3zryuAyc7I8AUkvRdWrXMDLjjsL5vuCTNwWuiY@main.internal.php.net> |
Issue: https://github.com/php/php-src/issues/20632
Author: IMSoP
### Description
When a "non-numeric" string is coerced to an integer or float, PHP raises an error rather than proceeding with the implicit cast. This is a good thing.
However, the error message implies that _any_ string would be invalid, rather than that the _content_ of the string is the problem.
Additionally, a common cause in my experience is that the string is _empty_, for instance, missing from some input data. It would be helpful for debugging to highlight when this is the case.
## Proposal
When coercion to a numeric, float, or int context fails:
* If the string being coerced is empty, use "empty string" as a pseudo-type in the error message
* Otherwise, use "non-numeric string" as a pseudo-type in the error message
## Current Behaviour
Mathematical operators:
```php
echo 1 + "1";
// 2
echo 1 + "hello";
// TypeError: Unsupported operand types: int + string
echo 1 + "";
// TypeError: Unsupported operand types: int + string
```
Function calls in coercive-call mode:
```php
declare(strict_types=0);
function foo(int $a) { echo $a; }
foo("1");
// 1
foo("a");
// TypeError: foo(): Argument #1 ($a) must be of type int, string given
foo("");
// TypeError: foo(): Argument #1 ($a) must be of type int, string given
```
## Proposed behaviour
Mathematical operators:
```php
echo 1 + "1";
// 2
echo 1 + "hello";
// TypeError: Unsupported operand types: int + non-numeric string
echo 1 + "";
// TypeError: Unsupported operand types: int + empty string
```
Function calls in coercive-call mode:
```php
declare(strict_types=0);
function foo(int $a) { echo $a; }
foo("1");
// 1
foo("a");
// TypeError: foo(): Argument #1 ($a) must be of type int, non-numeric string given
foo("");
// TypeError: foo(): Argument #1 ($a) must be of type int, empty string given
```