PHP 调试技巧之研修

文章目录

    最近调试 ecshop, 越发觉得自己的 PHP 调试技能不足,定位问题效率不够高。所以决定建个专题,把解决问题过程中学到的调试技巧记录一下

    var_dump

    页面中输出 array 很方便调试。但是,var_dump 的输出是没有排版的,也就是“一行流”,当要查看的信息量很大时,定位是件异常痛苦的事情。例如:

    $a = array ("laravel", "php", array ("vuejs", "angularjs", "reactjs"));
    var_dump($a);
    
    // 输出结果
    array(3) { [0]=> string(7) "laravel" [1]=> string(3) "php" [2]=> array(3) { [0]=> string(5) "vuejs" [1]=> string(9) "angularjs" [2]=> string(7) "reactjs" } }
    

    查到一种更方便的调试方式,如下

    $a = array ("laravel", "php", array ("vuejs", "angularjs", "reactjs"));
    echo '<pre>' . var_export($a, true) . '</pre>';
    
    // 输出结果
    array (
      0 => 'laravel',
      1 => 'php',
      2 => 
      array (
        0 => 'vuejs',
        1 => 'angularjs',
        2 => 'reactjs',
      ),
    )
    

    显然使用 var_export 这种方式输出的调试信息更具有可读性。于是,我在 vim snippets 中将 var_dump 映射到了 var_export 的这种方式。

    error_log 写入本地日志文件

    $logofile ='debug.log';
    error_log("volunm price: ".$volume_price, 3, $logofile);
    error_log("\n", 3, $logofile);
    

    注意,日志输出后加入换行符,否则格式混乱。

    error_log 的文档

    error_log — Send an error message to the defined error handling routines
    
    bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )
    
    3	message is appended to the file destination. A newline is not automatically added to the end of the message string.
    

    error_log 记录 array

    $logofile ='debug.log';
    error_log(print_r($price_list, true), 3, $logofile);
    error_log("\n", 3, $logofile);
    

    如果不加 print_r , 会显示成 Array,不显示具体的数据。

    输出效果

    Array
    (
        [0] => Array
            (
                [number] => 10
                [price] => 9.00
                [format_price] => ¥9元
            )
    
    )
    

    print_r 的使用文档

    print_r — Prints human-readable information about a variable
    所以,r 大概是 readable 的缩写。
    
    第二个参数,When this parameter is set to TRUE, print_r() will return the information rather than print it.
    

    Laravel 中记录 object 日志

    Log::info(print_r($result, true));
    
    [2019-04-19 09:11:40] production.INFO: stdClass Object
    (
        [Recommend] => https://error-center.aliyun.com/status/search?Keyword=MissingPhoneNumbers&source=PopGw
        [Message] => PhoneNumbers is mandatory for this action.
        [RequestId] => xxxx
        [HostId] => dysmsapi.aliyuncs.com
        [Code] => MissingPhoneNumbers
    )
    

    参考

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式