use of assertions for type checking in php?

Posted by user151841 on Stack Overflow See other posts from Stack Overflow or by user151841
Published on 2010-05-11T19:41:44Z Indexed on 2010/05/11 19:44 UTC
Read the original article Hit count: 343

Filed under:
|
|
|

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.");
}

Saves some typing

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

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

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

© Stack Overflow or respective owner

Related posts about php

Related posts about oop