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

  1. <?='<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.

  1. <?php
  2. /*
  3. Seriously, wtf?
  4. */
  5. function wtf($var, $arrayOfObjectsToHide=array(), $fontSize=11)
  6. {
  7. $text = print_r($var, true);
  8. $text = str_replace('<', '&lt;', $text);
  9. $text = str_replace('>', '&gt;', $text);
  10. foreach ($arrayOfObjectsToHide as $objectName) {
  11. $searchPattern = '#(\W'.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
  12. $replace = "$1<span style=\"color: #FF9900;\">";
  13. $replace .= "--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)";
  14. $text = preg_replace($searchPattern, $replace, $text);
  15. }
  16. // color code objects
  17. $text = preg_replace(
  18. '#(\w+)(\s+Object\s+\()#s',
  19. '<span style="color: #079700;">$1</span>$2',
  20. $text
  21. );
  22. // color code object properties
  23. $pattern = '#\[(\w+)\:(public|private|protected)\]#';
  24. $replace = '[<span style="color: #000099;">$1</span>:';
  25. $replace .= '<span style="color: #009999;">$2</span>]'
  26. $text = preg_replace($pattern, $replace, $text);
  27. echo '<pre style="
  28. font-size: '.$fontSize.'px;
  29. line-height: '.$fontSize.'px;
  30. background-color: #fff; padding: 10px;
  31. ">'.$text.'</pre>
  32. ';
  33. }

Example:

  1. <?php
  2. class Buggy
  3. {
  4. public $foo;
  5. protected $bar;
  6. private $baz;
  7. public function __construct()
  8. {
  9. $this->foo = 'no foo for you';
  10. $this->bar = range(1, 10);
  11. $this->baz = new Buggier;
  12. }
  13. }
  14. class Buggier
  15. {
  16. protected $errors;
  17. public function __construct()
  18. {
  19. $this->errors = range(1,1000); // oh noes!
  20. }
  21. }
  22. $buggy = new Buggy;
  23. 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() <--)
)

Posted by Aaron Fisher at 4:38pm

0 Comments RSS

Login To Post A Comment

Don't have an account yet? Sign Up