Simple debug class (safe print_r)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
class Debug
{
    protected static function escape($text) {
        return htmlspecialchars($textENT_QUOTES'UTF-8');
    }

    protected static function clean($in) {
        if (is_array($in)) {
            // Because we might introduce new (or overwrite existing) keys when we escape them,
            // we build a new array $out instead of overwriting $in.
            $out = array();
            foreach ($in as $k => $v) {
                $out[self::escape($k)] = self::clean($v); // $v might be anything, call clean() again
            }
            $in $out;
        } elseif (is_numeric($in)) {
            $in '(<span style="color: #ff0000;">numeric</span>) '.$in// no cleaning necessary
        } elseif (is_bool($in)) {
            $in '(<span style="color: #ff0000;">bool</span>) '.($in 'true' 'false'); // print boolean value as string
        } elseif (is_object($in)) {
            // Convert object to string using print_r.
            $in '(<span style="color: #ff0000;">object</span>) <span style="color: #009900;">'.self::escape(print_r($intrue)).'</span>';
        } elseif (is_null($in)) {
            $in '(<span style="color: #ff0000;">null</span>)';
        } elseif (is_resource($in)) {
            $in '(<span style="color: #ff0000;">resource</span>)'// @todo add more info?
        } elseif (is_string($in)) {
            $in '(<span style="color: #ff0000;">string</span>) '.self::escape($in);
        } else {
            // something we missed
            $in '(<span style="color: #ff0000;">something</span>)';
        }
        return $in;
    }

    public static function dump($in$file=''$line='') {
        if (!empty($line) && !empty($file)) {
            echo '<b>variable dump in file '.$file.' on line '.$line.'</b>';
        } else {
            echo '<b>variable dump</b>';
        }
        if (is_array($in)) {
            echo '<pre>'.print_r(self::clean($in), true).'</pre>';
        } else {
            echo '<pre>'.self::clean($in).'</pre>';
        }
    }
} // class
?>

Call with either Debug::dump($var) or Debug::dump($var, __FILE__, __LINE__).

If you use a character encoding that differs from UTF-8, you might want to consider to start using that. Otherwise change the third parameter of the htmlspecialchars() call to the (supported) character set you are using.