/** * 以字符串形式打印变量 * 本方法实现了 var_dump 和 print_r 类似的功能,但在处理复杂对象如 Yii 控制器时更强大。 * @param mixed $var 要打印的变量 * @param integer $depth dumper 要进入的变量的最大深度,缺省为 10 * @param boolean $highlight 结果是否语法高亮 * @return string 变量的字符串表现形式 */ public static function dumpAsString($var, $depth = 10, $highlight = false) { self::$_output = ''; self::$_objects = []; self::$_depth = $depth; self::dumpInternal($var, 0); if ($highlight) { $result = highlight_string("<?php\n" . self::$_output, true); self::$_output = preg_replace('/<\\?php<br \\/>/', '', $result, 1); } return self::$_output; }
/** * Exports a variable as a string representation. * * The string is a valid PHP expression that can be evaluated by PHP parser * and the evaluation result will give back the variable value. * * This method is similar to `var_export()`. The main difference is that * it generates more compact string representation using short array syntax. * * It also handles objects by using the PHP functions serialize() and unserialize(). * * PHP 5.4 or above is required to parse the exported value. * * @param mixed $var the variable to be exported. * @return string a string representation of the variable */ public static function export($var) { self::$_output = ''; self::exportInternal($var, 0); return self::$_output; }
/** * @param mixed $var variable to be exported * @param integer $level depth level */ private static function exportInternal($var, $level) { switch (gettype($var)) { case 'NULL': self::$_output .= 'null'; break; case 'array': if (empty($var)) { self::$_output .= '[]'; } else { $keys = array_keys($var); $outputKeys = $keys !== range(0, count($var) - 1); $spaces = str_repeat(' ', $level * 4); self::$_output .= '['; foreach ($keys as $key) { self::$_output .= "\n" . $spaces . ' '; if ($outputKeys) { self::exportInternal($key, 0); self::$_output .= ' => '; } self::exportInternal($var[$key], $level + 1); self::$_output .= ','; } self::$_output .= "\n" . $spaces . ']'; } break; case 'object': if ($var instanceof \Closure) { self::$_output .= self::exportClosure($var); } else { try { $output = 'unserialize(' . var_export(serialize($var), true) . ')'; } catch (\Exception $e) { // serialize may fail, for example: if object contains a `\Closure` instance // so we use a fallback if ($var instanceof Arrayable) { self::exportInternal($var->toArray(), $level); return; } elseif ($var instanceof \IteratorAggregate) { $varAsArray = []; foreach ($var as $key => $value) { $varAsArray[$key] = $value; } self::exportInternal($varAsArray, $level); return; } elseif (method_exists($var, '__toString')) { $output = var_export($var->__toString(), true); } else { $outputBackup = self::$_output; $output = var_export(self::dumpAsString($var), true); self::$_output = $outputBackup; } } self::$_output .= $output; } break; default: self::$_output .= var_export($var, true); } }