When developing or prototyping code, I find that I need a quick dump of information about the code I’m working on. This is not limited to just variables, but also function returns and other resources. I created this tiny function that can handle multiple variables and if the first parameter is the name of an export function it will use that for display.
function DumpVariables() {
// Get all of our variables
$Vars = func_get_args();
$VarCount = count($Vars);
// Determine dump function
switch ($Vars[0]) {
case 'print_r':
case 'var_export':
$DumpFunction = array_shift($Vars);
$VarCount--;
break;
default:
$DumpFunction = 'var_dump';
}
// Make our divider
$Line = str_repeat('-', 30);
foreach ($Vars AS $Sequence=>$Var) {
// Handle the first pass of the data
if (!isset($Check)) {
// Test for a shell to determine a web or shell environment
if (!isset($_SERVER['SHELL'])) {
print "<pre>\n";
}
// Header
print "Dumping {$VarCount} variables ".date('Y-m-d H:i:s')."\n";
$Check = true;
}
// Variable Header
print "\n\n {$Line} Variable {$Sequence} {$Line}\n\n";
$DumpFunction($Var); // Dump the variable
}
print "\n\n {$Line} End of Dump {$Line}\n"; // Footer
exit(0); // Kill the process because we are debugging
}
// Examples
DumpVariables('print_r', $myVar, get_class_methods($myClass), New MyClass);
DumpVariables($Session, $PostData, $DatabaseRecord->toArray());