note 127705 added to function.var-export

From: Date: Sat, 08 Oct 2022 13:02:40 +0000
Subject: note 127705 added to function.var-export
Groups: php.notes 
Request: Send a blank email to php-notes+get-219654@lists.php.net to get a copy of this message
Warning: var_export fails to create distinct property names if you have a private property in your class and one with the same name in a parent class. <?php class TestParent { private $priv = "Parent Private"; protected $prot = "Parent Protected"; public $pub = "Parent Public"; } class Test extends TestParent { private $priv = "Private Info"; protected $prot = "Protected Info"; public $pub = "Public Info"; } $t = new Test; var_export($t); Result: Test::__set_state(array( 'priv' => 'Private Info', 'prot' => 'Protected Info', 'pub' => 'Public Info', 'priv' => 'Parent Private', )) ?> To work around that problem, I created my own var_export, which also uses a more compact format, and using [] for arrays: <?php function var_export3($var, $indent = '') { if (is_array($var)) { $indent .= ' '; $ret = ''; $i = 0; $is_num = true; foreach ($var AS $idx => $value) { if ($ret != '') $ret .= ",\n"; if ($is_num && $idx === $i) { $i++; $ret .= $indent.var_export3($value, $indent); } else { $is_num = false; $ret .= $indent.var_export3($idx).'=>'.var_export3($value, $indent); } } if ($ret == '') return "[]"; return "[\n".$ret."]"; } else if (is_bool($var)) { return $var ? 'true' : 'false'; } else if (is_int($var) || is_float($var)) { return $var; } else if (is_string($var)) { if ($var === (string)(float)$var) return $var; return "'".str_replace(["\0", '\\', '\''], ["\\0", '\\', '\\\''], $var)."'"; } else if (is_object($var)) { $class = get_class($var); if ($class == 'stdClass') { $prefix = ; return "(object)".var_export3((array)$var, $indent); } else { return "$class::__set_state(".var_export3((array)$var, $indent).')'; } } } echo var_export3($t)."\n"; Result: Test::__set_state([ '\0Test\0priv'=>'Private Info', '\0*\0prot'=>'Protected Info', 'pub'=>'Public Info', '\0TestParent\0priv'=>'Parent Private']) ?> Note that replacement for non-printable characters is not complete. ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.159.161 (proxied: 217.248.145.30) ---- Manual Page -- https://php.net/manual/en/function.var-export.php Edit -- https://main.php.net/note/edit/127705 Del: integrated -- https://main.php.net/note/delete/127705/integrated Del: useless -- https://main.php.net/note/delete/127705/useless Del: bad code -- https://main.php.net/note/delete/127705/bad+code Del: spam -- https://main.php.net/note/delete/127705/spam Del: non-english -- https://main.php.net/note/delete/127705/non-english Del: in docs -- https://main.php.net/note/delete/127705/in+docs Del: other reasons-- https://main.php.net/note/delete/127705 Reject -- https://main.php.net/note/reject/127705 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219654) next »