wtf()
Thursday, September 15, 2011
Here is a little debugging function I wrote - it gets used way more than I'd like it to. This is basically a "fancy" print_r() for inspecting objects - the advantages are that it highlights the code, has the ability to supress the display of subobjects, and is a lot faster than typing
<?='<pre>'.print_r($var).'</pre>'; ?>
It's also fun to type wtf(), because that is usually what you are thinking when you're trying to debug something.
<?php
/*
Seriously, wtf?
*/
function wtf($var, $arrayOfObjectsToHide=array(), $fontSize=11)
{
$text = print_r($var, true);
$text = str_replace('<', '<', $text);
$text = str_replace('>', '>', $text);
foreach ($arrayOfObjectsToHide as $objectName) {
$searchPattern = '#(\W'.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
$replace = "$1<span style=\"color: #FF9900;\">";
$replace .= "--> HIDDEN - courtesy of wtf() <--</span>)";
$text = preg_replace($searchPattern, $replace, $text);
}
// color code objects
$text = preg_replace(
'#(\w+)(\s+Object\s+\()#s',
'<span style="color: #079700;">$1</span>$2',
$text
);
// color code object properties
$pattern = '#\[(\w+)\:(public|private|protected)\]#';
$replace = '[<span style="color: #000099;">$1</span>:';
$replace .= '<span style="color: #009999;">$2</span>]'
$text = preg_replace($pattern, $replace, $text);
echo '<pre style="
font-size: '.$fontSize.'px;
line-height: '.$fontSize.'px;
background-color: #fff; padding: 10px;
">'.$text.'</pre>
';
}
Example:
<?php
class Buggy
{
public $foo;
protected $bar;
private $baz;
public function __construct()
{
$this->foo = 'no foo for you';
$this->bar = range(1, 10);
$this->baz = new Buggier;
}
}
class Buggier
{
protected $errors;
public function __construct()
{
$this->errors = range(1,1000); // oh noes!
}
}
$buggy = new Buggy;
wtf($buggy, array('Buggier'));
Prints Out:
Buggy Object ( [foo] => no foo for you [bar:protected] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) [baz:private] => Buggier Object (--> HIDDEN - courtesy of wtf() <--) )