PHP Reference ยท Functions and Classes
PHP var_export() function
Reference for PHP var_export(): output a value as valid PHP code, the return flag, how floats, strings, objects and enums are written, and limits.
var_export() prints (or returns) a parsable PHP representation of a value: the code you would write to create that value. This makes it good for generating cache files, configuration arrays and test fixtures, and for showing exact values while debugging, because it distinguishes 1 from '1' and true from 1.
Unlike print_r() and var_dump(), the output is meant to be read by PHP itself, for example with include or eval.
var_export(mixed $value, bool $return = false): ?string
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
var_export(mixed $value, bool $return = false): ?string
| Name | Description |
|---|---|
$value |
The value to export. |
$return |
If true, return the code as a string instead of printing it. |
Return value: null when printing, the string when $return is true.
Usage notes
- Strings are single-quoted; only
'and\are escaped. Newlines are written literally, so the output stays valid PHP but may span lines. - Floats keep enough digits to restore the exact value (
0.30000000000000004), and whole floats are written with.0so the type survives (1.0). - Objects are written as
\ClassName::__set_state(array(...))(PHP 8.2 and later include the leading backslash). The class must implement a static__set_state()method for the code to work when evaluated.stdClassis exported as(object) array(...). - Enums export as
\Suit::Hearts, which is valid code and round-trips. - All visible state is included, also private and protected properties.
- Limits: resources are exported as
NULL, closures and objects with internal state produce__set_statetext that cannot be restored, and circular references produce a warning andNULL. - Array formatting uses the old
array (style with two-space indentation. Use[...]yourself if you need the short form (PHP does not offer an option). - Performance of generated files. Including a
var_exportfile is fast when OPcache is on, which is why frameworks cache configuration this way. Write atomically (temp file, then rename) to avoid half-written files. - Never
eval()untrusted output.
Related
var_dump()andprint_r(),serialize(),json_encode(),eval- Lessons: Debugging, Arrays