Programming - - By Harry Fuecks

Conditional Class Declaration – bad practice?

Was perturbed to read one on the comments on Zend’s PHP5 – Ask the Experts;

Q: In PHP 5 (rc1-dev)… is there any reason why you can’t do this?

if (!defined('SOMETHING')) {
class HelloWorld {
....
}
}

A: This is a problem we know about. In general, we don’t recommend doing conditional declarations of classes because it isn’t a very good programming practice. However it is yet unclear, if it will be supported, and it might be.

OK – in general to declare classes conditionally, for no other good reason than because you can, is probably a bad idea.

But as I was advocating here, there are very good reasons, IMO, why conditional declaration (i.e. conditional includes) are a good idea, the #1 being so that you can reduce the code “footprint” being included on every page request, when running your app on a typical shared PHP host (where PHP accelerators generally aren’t available).

If it’s a question of declaring which files are could be included in any given script up at the top, for the sake of readability etc., a simple tip via Jason Sweat, is something like;


if ( FALSE ) {
require_once 'dbconn.php';
require_once 'logger.php';
require_once 'auth.php';
// etc.
}

Although none of those classes will every be loaded at this point, it makes it easily visible what might get included in the script later on, so they’re visible to other developers and easy to document with phpDocumentor.

Could be I’m over reacting to a statement that just needs more qualification but makes me nervous to see it on Zend, from one of PHP’s core developers.

Sponsors