php / php/php-src

Use better error message for non-numeric strings in implicit contexts

未关闭
#20,632 4 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Feature Status: Verified
主要语言
C
星标
40.4k
派生
8.1k
平均合并
2 天 13 小时
30 天内合并 PR
96

描述

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:

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:

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:

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:

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 未指明文件或测试;首先在 php-src 中追踪数值强制转换和强制调用参数类型错误的路径,然后定位它们现有的覆盖范围。完成的标准是:在数学运算符和强制函数调用中,错误都能区分空字符串与其他非数字字符串。

由索引模型根据 Issue 内容生成。

评估

技术栈
php
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。