A handy PHP debug function

Like most developers, I often find it useful to spit out a few messages in the middle of a PHP script - especially when I’m debugging some problems.

Sadly, after only a few months our pristine code-base has become spotted with this, over and over again:

if (DEBUG) {
    echo "New user object: "; var_dump($user); echo "\n”;
}

After discovering var_export I felt like I’d improved things by switching to:

if (DEBUG) {
    printf("New user object: %s\n”, var_export($user, true));
}

I still didn’t like the fact that if (DEBUG) was appearing all over the place. So, after stumbling across call_user_func_array I’ve implemented by own debug function:

function debug()
{
    if (DEBUG)
    {
	$args = func_get_args();
	$args[0] = "<pre>" . $args[0] . "</pre>\n";
	for ($i = 1, $l = count($args); $i < $l; $i++) {
	    $args[$i] = htmlspecialchars(var_export($args[$i], true));
	}
	call_user_func_array('printf', $args);
    }
}

Which means I can remove all the if (DEBUG) statements, leaving only:

debug("New user object: %s", $user);

I think that’s much cleaner.

One Response to “A handy PHP debug function”

  1. Mariano Says:

    That’s a neat function there, I was looking for something like this. Thanks for sharing :)

Leave a Reply


Buy Viagra
Buy Viagra Online
Buy Generic Viagra
Discount Viagra
Order Viagra
Generic Viagra
Cheap Viagra
Viagra
Viagra Online
Purchase Viagra
Viagra Sale
Order Viagra Online
Online Viagra
Viagra Cheap
Buy Viagra Cheap
buy acomplia
Buy Cialis
Buy Cialis Online
Buy Generic Cialis
Discount Cialis
Order Cialis
Generic Cialis
Cheap Cialis
Cialis
Cialis Online
Purchase Cialis
Cialis Sale
Order Viagra Online
online viagra
cheapest viagra
cheap viagra online
viagra order
Buy Levitra
Cheap Levitra
Order Levitra
buy propecia
cheap propecia
propecia online
Buy Flomax
Buy Zoloft
Buy Xanax
Cheap Xanax
Generic Xanax
Order Xanax
buy neurontin
buy wellbutrin
buy lexapro
buy prozac
buy paxil
buy soma
cheap soma
buy tramadol
soma online
cheap tramadol
tramadol online
buy phentermine
cheap phentermine
order phentermine
phentermine online
buy fosamax
buy hoodia
buy levaquin
buy accutane
buy zyban
buy provigil
buy xenical
buy amoxicillin
buy augmentin
buy cipro
buy zithromax
buy zovirax