note 107120 deleted from function.debug-print-backtrace by danbrown

From: Date: Mon, 09 Jan 2012 18:06:43 +0000
Subject: note 107120 deleted from function.debug-print-backtrace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185476@lists.php.net to get a copy of this message
Note Submitter: ari dot n dot schulman at gmail dot com ---- A commenter below (Chris Kistner) provides a very useful function for returning the same information provided by debug_print_backtrace(), but safe when using ob_start() [output buffering]. However, this function throws bugs when used in certain circumstances, such as to print the 0-index backtrace (typically the custom error function itself), and when the arguments array for a function call itself contains any arrays. The below function fixes these problems: <?php function get_debug_print_backtrace($traces_to_ignore = 0){ $traces = debug_backtrace(); $ret = array(); foreach($traces as $i => $call){ if ($i < $traces_to_ignore ) { continue; } $object = ''; if (isset($call['class'])) { $object = $call['class'].$call['type']; if (is_array($call['args'])) { foreach ($call['args'] as &$arg) { get_debug_print_backtrace_get_arg($arg); } } } $ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ').$object.$call['function'].'('.obsafe_print_r($call['args'], true) .')'.(isset($call['file']) && isset($call['line']) ? ' called at ['.$call['file'].':'.$call['line'].']' : ''); } return implode("\n",$ret); } /** Explanation of this function available at http://us.php.net/manual/en/function.print-r.php . */ function obsafe_print_r($var, $return = false, $html = false, $level = 0, &$visitedVars = array()) { $spaces = ""; $space = $html ? "&nbsp;" : " "; $newline = $html ? "<br />" : "\n"; for ($i = 1; $i <= 6; $i++) { $spaces .= $space; } $tabs = $spaces; for ($i = 1; $i <= $level; $i++) { $tabs .= $spaces; } if (is_array($var)) { $title = "Array"; } elseif (is_object($var)) { $title = get_class($var)." Object"; } $output = $title . $newline . $newline; foreach ($var as $key => $value) { if (is_array($value) || is_object($value)) { if (isset($visitedVars[md5(serialize($value))])) { $value = '*RECURSION*'; } else { $visitedVars[md5(serialize($value))] = true; $level++; $value = obsafe_print_r($value, true, $html, $level, $visitedVars); $level--; } } else { $value = '('.gettype($value).') '.(is_string($value) ? '"' : '').$value.(is_string($value) ? '"' : ''); } $output .= $tabs . "[" . $key . "] => " . $value . $newline; } if ($return) return $output; else echo $output; } ?>

« previous php.notes (#185476) next »