Symfony2 issue: serialize() must return a string or NULL

December 18th 2012

serialize() must return a string or NULL

Have you ever seen this error in a Symfony2 project:

SymfonyBundleFrameworkBundleDataCollectorRequestDataCollector::serialize() must return a string or NULL

It was a right pain for me as searching on Google did not really return anything. If you search now you actually get the correct help from a stackoverflow post.

This error occurs when Symfony2 tries to serialize an entity. Serializing a class does not include the private class variables in the serialized string. This means unserializing the string results in missing information from the entity object if any of the entity class variables are private. The most common occurrence for me is when I have a relationship with one side of the relationship having an ArrayCollection of the other side's entities. If the entity that is related has private fields, this error pops up. The simple solution to this error is to make all private class variables protected:

private $id

// becomes

protected $id

//etc for all fields

I am not sure why the Symfony2 command line entity generator creates entities with class variables private as default but it does so remember to replace private with protected each time you generate an entity.

Luke Rotherfield

Symfony2 Developer in CT USA. Luke is a Symfony2 wizard and has written some sweet libraries of his own. Luke loves Jesus, his gorgeous wife and his two beautiful daughters :)