gpt4 book ai didi

php - 在 PHP 中使用断言进行类型检查?

转载 作者:可可西里 更新时间:2023-10-31 23:44:20 26 4
gpt4 key购买 nike

我使用异常抛出函数对我的 php 类中的参数进行了一些检查。我有一些函数可以进行基本检查(===in_array 等)并在 false 时抛出异常。所以我可以做 assertNumeric($argument, "\$argument is not numeric."); 而不是

if ( ! is_numeric($argument) ) {
throw new Exception("\$argument is not numeric.");
}

节省一些输入

我正在阅读 php manual page on assert() 的评论那个

As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool

那么,我是不是“做错了”?还有哪些其他/更好的方法可以做到这一点?

最佳答案

就我个人而言,我会支持维基百科内容,而不是使用断言进行常规类型检查。

相反,我会使用 PHP Type-Hinting(目前处理 php 5.1 的对象和 php 5.2 的数组......不会帮助您处理基本数据类型,但总比没有好);然后,您可以使用您所暗示的功能,甚至可以更进一步并考虑 Ilia Alshanetsky 的通用类型提示补丁。 See here .

关于php - 在 PHP 中使用断言进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2813917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com