PHP debug_backtrace [man]函数对于了解在何处调用函数/方法非常有用。
它打印代码的后跟踪。
示例:在当前使用的框架中,有ORM类来访问DB。因此,需要很长时间才能了解在需要时在哪里启动查询。解决方案:在全局变量(或类的字段)中保存已启动查询的列表以及已启动每个查询的代码。
代码:
class DB { # … public function query($query) { if (DEBUG_MODE) { ## $_dbt = debug_backtrace(); $_fromFile = isset( $_dbt[0]['file']) ? str_replace(_ROOT, “”,$_dbt[0]['file']) : “”; $_fromLine = isset( $_dbt[0]['line']) ? $_dbt[0]['line'] : “”; $_launchedFrom = “launched from $_fromFile:$_fromLine“; $this->logQueries[] = “[$query][$_launchedFrom]“; # ..query. } } # … }
结果示例:
Array ( [0] => [set names utf8][launched from C:\wamp\www\dev\index.php:68] [1] => [SELECT * FROM `Setting` WHERE `id` = 1][launched from \class\Setting.class.php:20] [2] => [SELECT id FROM `User`WHERE id = 293968 LIMIT 1][launched from \class\User.class.php:598] [3] => [SELECT * FROM `User` WHERE `id` = 293968][launched from \class\User.class.php:45] [4] => [SELECTf.store_idFROM `Store_Monthly_Featured` f ORDER BYf.orderASC][launched from \class\Store_Monthly_Featured.class.php:16] )
仅打印行和数字的有用功能
function debug_backtrace_filelines() { $ret = array(); $b = debug_backtrace(); foreach ($b as $elements) { $ret[] = $elements['file'].‘:’.$elements['line']; } }