• Blogs (9)
    • šŸ“± 236 - 992 - 3846

      šŸ“§ jxjwilliam@gmail.com

    • Version: ā€šŸš€ 1.1.0
  • 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:

    1. For array and hash, using print_r() or var_dump() to output.
    2. For scalar variables, just simply use echo.
    3. 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.