开发者

PHP debugging: combine foreach and exit

While debugging, it would h开发者_如何转开发elp if I could exit() and use a foreach to print individual elements of an array. Any ideas?


If you want to easily print the contents of an array or any other PHP value, use var_dump. Calling exit() is orthogonal to this, and I think it's quite clear to write:

var_dump($arr);
exit(1);

Another technique is to log your output, which is potentially more useful if you don't want to sift through your output HTML to look for the output of var_dump:

error_log(var_export($arr));
exit(1);


perhaps you could make a debug exit function for debugging with print_r (prints a human-readable version of a variable)

function dexit($array, $status = 0) {
    print_r($array);
    exit($status);
}

then, anywhere in your code, you could just

dexit($array);
// or
dexit($array, 0);

but it's not difficult to just use the print_r inline either way :)


Doesn't sound like the most ideal way to debug IMHO, but this could be achieved by using register_shutdown_function():

http://php.net/manual/en/function.register-shutdown-function.php

e.g:

    function debug_print_array(){
           global $array;
           foreach($array as $key => $val){
                echo "$key: $val\n";      
           }
    }

register_shutdown_function('debug_print_array');


Try this, you have two option, debug or var_dump

function debug_exit($array, $type = 1) {
    if ($type == 1) { print_r($array); } 
    if ($type == 2) { var_dump($array); } 
    exit();
}


Here is what I use for that, x_r(). The trace comes from this example in PHP docs. The reason for the trace is so you/others can find aprx where/what x_r() is being called via. The exit() is optional if you need to see theme for some reason under the print_r():

// Exits with a print_r and call trace for debugging

if (!function_exists('x_r')) {
    function x_r($obj, $exit = true, $return = true) {

        // echo the obj first
        echo '<pre style="background: #FFFFFF;">', print_r($obj, $return), '</pre>';

        // include a debug call trace
        $e = new Exception();
        $trace = explode("\n", $e->getTraceAsString());

        // reverse array to make steps line up chronologically
        $trace = array_reverse($trace);
        array_shift($trace); // remove {main}
        array_pop($trace); // remove call to this method
        $length = count($trace);
        $result = array();

        for ($i = 0; $i < $length; $i++) {
            $result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
        }

        // echo call trace
        echo '<pre style="background: #FFFFFF;">', print_r($result, $return), '</pre>';

        if ($exit === true) {
            exit();
        }
    }
}

Here is the Gist: https://gist.github.com/dhaupin/d9d48328dbe312f6c0de

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜