Runtime Variable Inspection

The most common way to debug is to stick echo statements into your code at strategic places. If you are feeling clever, you might even output a variable's value too:

echo "<p>here: \$myvar = $myvar";</p>

I call this runtime variable inspection and as PHP is a script language, it's a very fast way to debug a script. You stick the echo statement at strategic points and with a few page refreshes in the browser, you have the troublesome bit of code nailed.

However

echo $var

doesn't really cut it for variables or objects (or booleans for that matter). To this end I wrote myself a function called DB() to print out a variety of variables sensibly.

The code looks like this:

function DB($var, $title='', $echo_to_screen = true)
{
  if($title)
    $titleText = "Debug display of '$title':";
  else
    $titleText = "Debug: ";

  ob_start();
  echo "<p><b>$titleText</b><pre>\n";
  if(is_array($var))
  {
    echo "Number of elements: " . count($var) . "\n";
    print_r($var);
  }
  elseif(is_object($var))
  {
    print_r($var);
  }
  elseif(is_string($var))
  {
    print_r(htmlentities(str_replace("\t",'  ',$var)));
  }
  elseif(is_bool($var))
  {
    echo $var === true ? 'true' : 'false';
  }
  else
  {
    print_r($var);
  }

  echo "</pre></p>\n";
  $output = ob_get_contents();
  ob_end_clean();

  if($echo_to_screen)
  {
    echo $output;
  }

  return $output;
}

It works wonders for fixing nearly all the bugs I have to deal with. Anything more complicated usually means that I break out the proper debugger in Zend Studio (wish they had a Firefox toolbar!)

Leave a Reply

Pre order