New in Symfony 4.2: VarExporter component
September 27, 2018 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
In Symfony applications, the VarDumper component provides a dump()
function
as a better alternative to PHP's var_dump()
function. In Symfony 4.2, we're
introducing a new VarExporter
component to provide a better alternative to
PHP's var_export()
function.
The var_export()
function outputs or returns a parsable string
representation of a variable. It is similar to var_dump()
with one
exception: the returned representation is valid PHP code. Symfony's export()
function is similar, but adds lots of useful features to it.
Consider the following example, where a simple array is exported:
1 2
$data = array(123, array('abc'));
$result = VarExporter::export($data);
The output is similar to what you'd expect when using var_export()
, although
export()
generates valid and PSR-2 compliant PHP code:
1 2 3 4 5 6 7 8
<?php
return [
123,
[
'abc',
],
];
The main difference is that export()
, unlike var_export()
preserves all
the semantics associated with the serialization mechanism of PHP (__wakeup
,
__sleep
, Serializable
). Consider this example of a class implementing
Serializable
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class MySerializable implements \Serializable
{
public function serialize()
{
return '123';
}
public function unserialize($data)
{
// do nothing
}
}
$data = array(new MySerializable(), new MySerializable());
$result = VarExporter::export($data);
The result looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php
return \Symfony\Component\VarExporter\Internal\Configurator::pop(
\Symfony\Component\VarExporter\Internal\Registry::push([], [], [
'C:50:"Symfony\\Component\\VarExporter\\Tests\\MySerializable":3:{123}',
]),
null,
[],
[
\Symfony\Component\VarExporter\Internal\Registry::$objects[0],
\Symfony\Component\VarExporter\Internal\Registry::$objects[0],
],
[]
);
In addition to producing better results, if your application uses OPcache,
Symfony's export()
function is faster and more memory efficient than
serialize()
and even igbinary.
Finally, Symfony's export()
function includes other improvements over
var_export()
and serialize()
:
- The generated output can be re-indented without messing up with
\r
or\n
in the data; - Missing classes throw a
ReflectionException
instead of being unserialized toPHP_Incomplete_Class
objects; - References involving
SplObjectStorage
,ArrayObject
orArrayIterator
- instances are preserved;
- References involving
Reflection*
,IteratorIterator
andRecursiveIteratorIterator
classes- throw an exception when being serialized.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.