PHP: a lightweight function for output intermediate results
Blogs20122012-10-09
PHP: a lightweight function for output intermediate results.
In PHP, Except you use xdebug extension, the Intermediate results can be written in various ways. Here I list an effective, simply, convenient way which I used to make work easier. The purpose:
- For array and hash, using print_r() or var_dump() to output.
- For scalar variables, just simply use echo.
- Have the switch flag to open and close the output conveniently.
Here it is:
function __p($vars, $debug=true) {
if (!$debug) return;
if (is_array($vars) || is_object($vars)) {
echo "<pre>";
print_r($vars);
echo "</pre>";
} else
echo $vars . "<br>n";
}The default switch flag, ā$debugā is set to ātrueā by default, so it can be used to output whatever you want to output:
// 1. for variable:
$sql = 'select ...'.mysql_real_escape_string($str);
__p($sql);
//2. for function:
function foo($params) {...}
__p(foo($params);And later, if test ok, donāt need the output, just change the default switcher ā$debugā to false:
__p($sql, false);
__p(foo($params), false);You can also set the ā$debugā as global constant variable, so as to control all the outputs by using a single switch flag. As an advanced example, the following is a way of using HTTP request to control the output:
if ($__REQUEST['test']) {
header('Content-Type: text/html; charset=utf-8');
__p($obj->foo());
exit;
}At Browserās URL part, everytime you add ātestā at end of the URI, like:
http://yoursite/your\_script?params**&test**
Instead of output all webpage, the output results will be redirect, and print out the intermediate results. That is useful for test and debug purpose. Of course, the function can be enhanced to add more features and better output.
