note 52188 deleted from function.var-export by aidan
| From: | aidan@php.net | Date: | Sun, 01 May 2005 04:59:56 +0000 |
| Subject: | note 52188 deleted from function.var-export by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-88815@lists.php.net to get a copy of this message | ||
Note Submitter: james at colossalus dot com
----
Ok, I am posting version 2 of the _var_export() script. The original script works ok when an array
is passed, but if it contained objects, they would not be exported (it would simply put a NULL in
its place and move on).
<?
function _var_export($var, $return=false) { //v2
$object_tree = array("\$this");
$object_index = 0;
$class_code = ""; $init_code = "";
if (!function_exists("_var_export_")) {
function _var_export_($var, &$object_tree, &$object_index, &$class_code,
&$init_code, $indent="") {
if (is_object($var)) {
$class_name = "_".get_class($var)."_"; // change class name to remove
conflict with ogirinal class
if ($class_code == "") {
$class_code = "new $class_name();\r\nclass $class_name {\r\n";
foreach ($var as $key => $value) {
$object_tree[++$object_index] = "->{$key}";
$class_code .= " var \$$key = "._var_export_($value, $object_tree, $object_index,
$class_code, $init_code, " ").";\r\n";
$object_index--;
}
$output = rtrim($output, ";\r\n")."\r\n$indent)\r\n";
} else {
$output = "NULL /*(object)$class_name*/";
foreach ($var as $key => $value) {
$object_tree[++$object_index] = "->{$key}";
$init_code_tmp .= "
".implode(array_slice($object_tree,0,$object_index),"")."->$key =
"._var_export_($value, $object_tree, $object_index, $class_code, $init_code, "
").";\r\n";
$object_index--;
}
$init_code = $init_code_tmp.$init_code;
return $output;
}
if ($init_code != "")
$class_code .= "\r\n function $class_name() {\r\n$init_code }\r\n";
$class = true; $class_code .= "}";
return $class_code;
} elseif (is_array($var)) {
if ($class_code == "") {
$class_code = " "; // so we dont start a class export
$object_tree[0] = "\$_array_init_";
$output = "&{$object_tree[0]}; ({$object_tree[0]} = array (\r\n";
$close_array = true;
} else $output = "array (\r\n";
foreach ($var as $key => $value) {
$object_tree[++$object_index] = "[$key]";
$output .= "$indent '$key' => "._var_export_($value, $object_tree,
$object_index, $class_code, $init_code, "$indent ").",\r\n";
$object_index--;
}
$output = rtrim($output, ",\r\n")."\r\n$indent)";
if ($close_array) {
$init_code = rtrim(");".rtrim("\r\n".$init_code,"\r\n"),
";"); // make sure we don't end wtih ';'
$output .= $init_code;
}
return $output;
} elseif (is_string($var) || $var == "") {
$output = "\"".addcslashes($var,
"\0..\37\"@\@\177..\377")."\"";
return $output;
} elseif (is_bool($var)) {
$output = ($var ? 'TRUE' : 'FALSE');
return $output;
} else {
return $var;
}
} }
$output = _var_export_($var, $object_tree, $object_index, $class_code, $init_code);
if ($return) return $output;
echo $output;
}
?>
Again, if it works, let me know! :)