PHP function for displaying the full contents of a variable - a customisable var_dump
<?php | |
/** | |
* Recursively iterates over $var, displaying each | |
* property/variable contained within | |
* @param mixed $var Variable of any type | |
* @param boolean $displayTypes Whether to display the types along with values | |
* @param integer $depth private var for telling how deep we are | |
* @return null always returns null | |
*/ | |
function display($var, $displayTypes = True, $depth = 0){ | |
$add = ''; | |
if($displayTypes){ | |
if(is_object($var)){ | |
echo 'Object: ' . get_class($var); | |
} else { | |
echo sprintf('%-7s',gettype($var)); | |
} | |
$add = ' '; | |
} | |
if(isIterable($var)){ | |
if($depth>0 || $displayTypes) echo "\n"; | |
if($displayTypes){ | |
echo $add.str_repeat(' ', $depth)."(\n"; | |
} | |
foreach($var as $key => $val){ | |
echo str_repeat(' ', $depth); | |
if($displayTypes){ | |
echo str_repeat($add, 2); | |
echo sprintf('%-7s',gettype($key)); | |
echo ' '; | |
} | |
if(is_string($key)){ | |
echo '["'.$key.'"]'; | |
} else { | |
echo '['.$key.']'; | |
} | |
echo " => "; | |
display($val, $displayTypes, $depth+1); | |
} | |
if($displayTypes){ | |
echo "".$add.str_repeat(' ', $depth).")\n"; | |
} | |
} else { | |
if($displayTypes){ | |
echo ' '; | |
} | |
if(is_string($var)){ | |
echo '"'.$var . "\"\n"; | |
} else { | |
echo $var . "\n"; | |
} | |
} | |
return null; | |
} | |
/** | |
* Determines if a variable is iterable or not | |
* @param mixed $var The input variable... | |
* @return boolean Whether we can iterate over it or not | |
*/ | |
function isIterable($var) { | |
set_error_handler(function ($errno, $errstr, $errfile, $errline, array $errcontext) | |
{ | |
throw new \ErrorException($errstr, null, $errno, $errfile, $errline); | |
}); | |
try { | |
foreach ($var as $v) { | |
break; | |
} | |
} catch (\ErrorException $e) { | |
restore_error_handler(); | |
return false; | |
} | |
restore_error_handler(); | |
return true; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment