通过自己PHP编码实现var_dump()方法
个人学习笔记
核心源码如下:
/** * 打印 * @param array ...$params * @author klinson <[email protected]> */ function info(...$params) { foreach ($params as $param) { info_item($param); } } /** * 打印单个变量 * @param $param * @param int $i * @author klinson <[email protected]> */ function info_item($param, $i = 0) { switch (gettype($param)) { case 'array': info_array($param, $i); break; case 'object': info_object($param, $i); break; case 'boolean': echo "bool(".($param ? "true" : "false").")"; break; case 'integer': echo "int({$param})"; break; case 'string': echo "string({$param})"; break; case 'double': echo "float({$param})"; break; case 'null': echo 'null'; break; case 'resource': echo 'resource'; break; default: echo 'UNKNOWN TYPE'; break; } echo PHP_EOL; } /** * 打印数组 * @param $param * @param int $i * @author klinson <[email protected]> */ function info_array($param, $i = 0) { // 前置空格 $space = ''; $num = $i; while ($num) { $space .= ' '; $num--; } echo 'array['.count($param).']: {'.PHP_EOL; foreach ($param as $key => $item) { echo $space." [{$key}] => "; info_item($item, $i+1); } echo $space.'}'; } /** * 打印对象 * @param $param * @param int $i * @author klinson <[email protected]> */ function info_object($param, $i = 0) { // 前置空格 $space = ''; $num = $i; while ($num) { $space .= ' '; $num--; } echo 'object('.get_class($param).'['.count($param).']): {'.PHP_EOL; foreach ($param as $key => $item) { echo $space." [{$key}] => "; info_item($item, $i+1); } echo $space.'}'; }
测试代码:
$a = 1.11; $b = 'a'; $c = [$a, $b]; $d = new stdClass(); $d->aaa = 'aaa'; $d->bb = $c; info($a, $b, $c, $d);
效果如下:
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23