Currently reading: Stories of Your Life and Others by Ted Chiang

Debug PHP variables discreetly

If you don't have Xdebug involved in your current project, you may be relying on var_dump or var_export to check on things while coding. Depending on where in the code this happens, their output can get in the way of the rendering of a given page or be hard to read given where it lands ⸺ in one part of a three-column block, for instance.

Unless you have a debugging setup that pushes its output out of the way, possibly outside of the layout entirely with fixed positioning, you may want to drop it into the browser's JS console instead.

function console_dump($stuff) {
	echo '<script> console.log(' . json_encode($stuff) . ') </script>';
}

As log() isn't the only method exposed by the console object, you could easily expand on this a bit to allow for use of things like info(), warn(), and assert().

function console_dump($stuff, $fn = 'log') {
	echo "<script> console.{$fn}(" . json_encode($stuff) . ") </script>";
}

My preference when building WP sites hasn't been to do it this way because of… reasons. I usually send debug output down to below the footer via hook instead. Maybe I'll do this console stuff instead next time.

function footer_dump(…$vars) {
    foreach ($vars as $var) {
        add_action('shutdown', function () use ($var) {
            echo '<pre>', var_export($var, true), '</pre>';
        }, 9999);
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *