This is a simple little PHP function I created back when I fist came across the var_export() function. It combines it with the power of highlight_string() to bring quick debugging to a new level. I've been using this for years now, but until recently, didn't have this blog. I figured this would a be a good bit of code to start off with:
My printr() function:
<?php
/**
* printr() - Highlights exported variable
*
* @param mixed $var Variable to export
* @param string $name Name of the variable
* @param bool $echo Print or Return it?
* @return mixed
**/
function printr($obj, $name='$obj', $echo = TRUE) {
$str = var_export($obj, 1);
$str = "<?php\n$name = $str;\n?>\n";
$str = highlight_string($str, true);
$str = '<pre>' . $str . '</pre>';
$str = preg_replace("/<br\s*\\/?>/", "\n", $str);
if ($echo) {
echo $str;
} else {
return $str;
}
}
?>
Samples:
Here are some samples of printr()'s output:
Code:
<?php
$a = Array('PHP','JavaScript','HTML');
printr($a);
?>
Output:
<?php
$obj = array (
0 => 'PHP',
1 => 'JavaScript',
2 => 'HTML',
);
?>
Code:
<?php
class testClass {
var $test1 = 'test1';
var $test2 = 'test2';
var $test3 = array('a','b');
}
$b = new testClass();
printr($b, '$b');
?>
Output:
<?php
$b = class testclass {
var $test1 = 'test1';
var $test2 = 'test2';
var $test3 =
array (
0 => 'a',
1 => 'b',
);
};
?>
Enjoy! =)