Debugging your own code

If your read this, then you might have playing with some code already - and as you know, nobody is perfect... all we make mistakes. But how you can find yours?

The old-fashioned way, used by all coders at a given time is simple: add some code to display the variables you use to see if they are behaving as you want. In our case, given the fact Joomla is PHP based, the simplest way to see what is going on inside your code is to temporarily add echo statements for variables (or print_r's for arrays) to show their values on the screen. For example, say you want to know what the value of some variables are when $i is "5". You could use code like this:

for ( $i = 0; $i < 10; $i++ ) {
	if ( $i == 5 ) {
		echo '$i=' . $i; 
                // other echo statements 
	}
}

The trick works, but the biggest caveat here is, that when everything works finally as you wish, you need to go back to your code, and to comment out or delete all those debug messages. But why don't do this in a much smarter way? Let's use Joomla's DEBUG mode to optionally display the needed debug  informations. The debug mode, since Joomla 1.5, can be set in the site's Global Configuration, System tab, Debug Settings section, Debug System radio button.

All you need is to check in your code if the website is in debug-mode, and optionally display the debug info. For this you need to test the JDEBUG - variable like this:

if(JDEBUG){
//whatever debugging code you want to run
}