通过自己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);

效果如下:

通过自己PHP编码实现var_dump()方法

相关推荐