September 27, 2018 Javier Eguiluz

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() :