If you’re used to working with models (in any foundation or framework, but specifically WordPress), then there’s a chance that you may need to serialize an instance of the model at some point.

Sure, writing the class to a database using PHP’s built-in functions is easy enough; however, introducing a bit of flexibility especially as it relates to making it available on other platforms is important.

For example, let’s say you’re building an application on WordPress that’s going to have some type of unique piece of information represented in a model. The model will then be accessible via a mobile application through the REST API.

WordPress Class Serialization: PHP

Arguably, one of the easiest ways to get this done is to use JSON. It’s a format that works across various languages and platforms, can be easily serialized and de-serialized by said platforms, and sent across the wire as needed.

And it’s incredibly easy to implement this in PHP. You just need to make sure your class implements the JsonSerializable interface.

WordPress Class Serialization: PHP

From the documentation, the interface does the following:

Objects implementing JsonSerializable can customize their JSON representation when encoded with json_encode().

The only method a class needs to provide is jsonSerialize, and though it’s likely you will want to serialize all of the properties of an object (as well as its state whenever its called), you can customize the implementation however you’d like.

WordPress Class Serialization

For example, if you have a class and you just want to implement its name property, then you’d implement the function like this:

If you wanted to add a little more complexity to it, then you may do this:

And if you wanted to go all in on serializing the properties, then you can implement a loop to build an array:

Whatever the case, when an instance of the class is passed to the json_encode function, it will invoke the jsonSerialize function on the object so that you get the representation of the object in JSON format as you’ve designed.

This is incredibly easy and helpful when it comes to providing using data across multiple platforms (or even the same platform, for that matter).