【问题标题】:Fatal error: Uncaught TypeError: Unsupported operand types: int + string on PHP 8.0.8致命错误:未捕获的 TypeError:不支持的操作数类型:PHP 8.0.8 上的 int + string
【发布时间】:2021-09-28 07:49:51
【问题描述】:

我正在将 35,578,926 之类的数字格式转换为 35.5M(或百万)之类的短字。我的代码在 PHP 7.4 上运行良好,在最新版本 8.0.8 上发生致命错误。

function convert($n)
{
    $n = (0 + str_replace(",", "", $n));
    if (!is_numeric($n)) return false;
    if ($n > 1000000000000) return round(($n / 1000000000000) , 1) . 'T';
    else if ($n > 1000000000) return round(($n / 1000000000) , 1) . 'B';
    else if ($n > 1000000) return round(($n / 1000000) , 1) . 'M';
    else if ($n > 1000) return round(($n / 1000) , 1) . 'K';
    return number_format($n);
}
$n = '35578926';

在 PHP 7.4 上,此代码返回输出:

$n = convert('35578926'); 
echo $n; // 35.5M

我尝试改变

$n = (0 . str_replace(",", "", $n)); // this resolve nothing but no error 


$n = null; // also this resolve nothing but no error

那么如何在 PHP 8.0.8 上将此数字(35578926 或 35,578,926)转换为 35.5M 之类的短字?

【问题讨论】:

  • 你的代码没有对我发出任何警告:3v4l.org/Qdl5V 但是你也可以强制转换为 int 或 float inside
  • 您遇到了什么错误?我只能访问 8.0.0,您的代码可以正常工作。
  • 我在 php 8.0.8 xampp 上收到了这个“致命错误:未捕获的类型错误:不支持的操作数类型:int + string”
  • 我在某处读到过:更改转换规则,以便 '0e55' == '0e99' 之类的结构不会返回 true。我会将分配行更改为$n = intval(str_replace(",", "", $n));
  • 改成$n = intval(str_replace(",", "", $n)); 就可以了

标签: php php-8


【解决方案1】:

我怀疑这行代码是由比 PHP 更熟悉 JavaScript(或其他语言)的人编写的:

$n = (0 + str_replace(",", "", $n));

在 JavaScript 中,这里的“0 +”是强制值是“数字”而不是字符串的惯用方式。但是,在 PHP 中,有 explicit cast operators 用于此目的,以及单独的整数和浮点类型,因此该行应该是:

$n = (int)str_replace(",", "", $n);

或:

$n = (float)str_replace(",", "", $n);

这里还有一个bug,就是这行来得太晚了:

if (!is_numeric($n)) return false;

目前,这是在将字符串转换为数字之后运行,因此它不可能不是数字。这会更有意义:

$n = str_replace(",", "", $n);
if (!is_numeric($n)) return false;
$n = (float)$n;

请注意,is_numeric 对“数字”的定义非常广泛,因此如果您实际上只需要整数,则可能需要 ctype_digit

$n = str_replace(",", "", $n);
if (!ctype_digit($n)) return false;
$n = (int)$n;

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多