Kint是一个超级加强版的var_dump,使用很简单:
<?php
Kint::dump($GLOBALS, $_SERVER);

除此以外,Kint还支持用modifier改变输出的结果:
<?php
+Kint::dump($data); // Disabled depth limit
!Kint::dump($data); // Expand all data in this dump automatically
@Kint::dump($data); // Return the output of this dump instead of echoing it
...
虽然这是PHP的语法,但是一个函数怎样根据函数调用前的符号改变自己的行为呢?
想起之前写过一个输出变量和类型的函数:
function var_types() {
$bt = debug_backtrace()[0];
$file = new \SPLFileObject($bt['file']);
$file->seek($bt['line'] - 1);
$line = $file->current();
$matchs = null;
preg_match('/var_types\((.*)\)/', $line, $matchs);
$param_names = array_map('trim', explode(",", $matchs[1]));
$args = func_get_args();
for ($i = 0; $i < count($args); $i++) {
echo $param_names[$i] . ' ' . gettype($args[$i]) . PHP_EOL;
}
}
原理是通过debug_backtrace
拿到函数调用的位置(文件+行数),然后去解析文件。通常用PHP(而不是C扩展)实现var_dump
,都是类似的方法。Kint也不例外,只是它的解析更强大:SourceParser.php。
网友评论