Become a Patron!

My Amazon wishlist can be found here.

Life Line

var_export and classes

Today I stumbled upon an old problem while using var_export() on an array with objects. var_exports()'s description is " Outputs or returns a parsable string representation of a variable ", but it didn't work to well in this case:

array (
  0 =>
  class ezcTranslationData {
    public $original = 'Node ID:';
    public $translation = 'Knoop ID:';
    public $comment = false;
    public $status = 0;

This snippet above can of course not be parsed as valid PHP code. After thinking about it for a bit, I came up with a solution. Instead of the code above, we now generate:

array (
  0 =>
    'original' => 'Node ID:',
    'translation' => 'Knoop ID:',
    'comment' => false,
    'status' => 0,

The __set_state() method is then required to be implemented by the class for this to work, but that is better than generating code which can never be parsed. The name comes from the Memento pattern . As this fixes a bug this made it into PHP 5.1.0 and PHP 6.0.0.


This article has a short URL available:


No comments yet

Add Comment


Will not be posted. Please leave empty instead of filling in garbage though!

Please follow the reStructured Text format. Do not use the comment form to report issues in software, use the relevant issue tracker. I will not answer them here.

All comments are moderated