【发布时间】:2020-11-18 06:18:05
【问题描述】:
在 JavaScript 中,如果函数的参数是无效类型,这就是我创建抛出错误的方式。
function myFunction(num)
if (typeof(num) !== 'number') {
throw TypeError('num cannot be' + num);
}
}
我如何在 PHP 上做到这一点?我知道有一个 throw 命令,但你如何设置错误类型。在上面的 JavaScript 示例中我将其设置为 TypeError,如何设置 PHP 抛出错误的错误类型以及 PHP 中的错误类型是什么?
function myFunction($num)
if (gettype($num) !== 'boolean') {
throw new Exception('$num cannot be ' , $num);;
}
}
【问题讨论】:
-
php 有 is_type 命令。如果您想要控制布尔值,请使用
if(!is_bool($num))php.net/manual/en/function.is-bool.php 中的详细信息 -
if (!is_bool($num)) throw new Exception('$num can not be ' . $num); -
PHP 有异常类:php.net/manual/en/spl.exceptions.php
-
如果您使用的是 PHP 7,只需指定参数类型:
function myFunction(bool num)和 enable strict types。无需执行任何其他操作,只需使用已有的语言功能即可。