从字符串转换为 int 导致精度损失时如何抛出异常?

how can I throw an exception when casting from string to int caused precision loss?

有没有办法在从字符串转换为 int 之前或之后实际检查是否存在精度损失并引发异常?

$id = "21321312412435453453453454"
$numId = (int) $id;

这应该适合你:

(刚用phppredefined constants比较了一下)

$id = "21321312412435453453453454";
if($id > PHP_INT_MAX)
    echo "too big";
else
    echo "okay";

输出:

too big

编辑:

对于负数,你可以这样定义常量:

define('PHP_INT_MIN', ~PHP_INT_MAX); 

您甚至可以在手册中阅读有关 PHP_INT_MAX 的信息:http://php.net/manual/en/language.types.integer.php

引自那里:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

尝试将其转换回字符串并比较两者。