在PHP中使用断言进行类型检查? [英] use of assertions for type checking in php?

查看:88
本文介绍了在PHP中使用断言进行类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用异常抛出函数对php类中的参数进行了检查.我具有执行基本检查的功能(===in_array等),并在false上引发异常.所以我可以做assertNumeric($argument, "\$argument is not numeric.");代替

I do some checking of arguments in my classes in php using exception-throwing functions. I have functions that do a basic check ( ===, in_array etc ) and throw an exception on false. So I can do assertNumeric($argument, "\$argument is not numeric."); instead of

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

保存一些键入内容

我正在阅读assert()上 php手册页的评论

I was reading in the comments of the php manual page on assert() that

如Wikipedia上所述-断言 主要是一种开发工具,他们 通常在程序被禁用时被禁用 向公众发布."和 应使用断言来记录 逻辑上不可能的情况,以及 发现编程错误-如果 不可能"发生,然后发生 基本面显然是错误的.这是 与错误处理不同:大多数 错误条件是可能的, 尽管有些可能非常极端 在实践中不太可能发生.使用 断言为通用错误 处理机制通常是不明智的: 断言不允许优雅 从错误和断言中恢复 失败通常会终止程序的 突然执行.断言也可以 不显示用户友好错误 消息."

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."

这意味着 强制使用"gk at proliberty dot com" 启用断言,即使在 他们已经被手动禁用,去 反对仅使用的最佳做法 它们作为开发工具

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

那么,我是做错了"吗?还有什么其他/更好的方法?

So, am I 'doing it wrong'? What other/better ways of doing this are there?

推荐答案

我个人是第二本Wikipedia内容,并且不使用断言进行常规类型检查.

Personally I'd second Wikipedia content and not use assertions for regular type checking.

相反,我将使用PHP Type-Hinting(当前在php 5.1和php 5.2之上的数组上工作……对基本数据类型没有帮助,但总比没有好).然后,您可以使用所提示的功能,甚至走得更远,并考虑使用Ilia Alshanetsky的修补程序进行通用类型提示. 请参见此处.

Instead, I'd use PHP Type-Hinting (currently working on objects as php 5.1 and arrays as of php 5.2 ...won't help you with basic data types, but it's still better than nothing); you can then use the functions you were hinting at or even go a little further and consider Ilia Alshanetsky's patch for general type hinting. See here.

这篇关于在PHP中使用断言进行类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆