JSONize your PHP classes using traits

I was having a discussion with a colleague regarding how to add generic JSON based representation to a number of classes without making a big effort. The immediate solution that came in my mind is to use the Traits for it (introduced in PHP 5.4).

So I wrote the following example for him:




The result of running the above code will be like this:

  • http://masnun.me masnun

    Pretty cool! :)

  • http://www.anmsaiful.com A.N.M. Saiful Islam

    Good post. Tobe vai eta kon account er info? :p

  • Anjan Bhowmik

    Same thing I used to do via class inheritance ๐Ÿ˜€

    Usefulness on trait will be felt when u have lots to functions and properties to be shared among many classes :) As Masnun said, really cool!

  • Nhm tanveer hossain khan

    Nice example :) Trait is about mixin different roles of a class.

  • http://joshadell.com Josh Adell

    Nice! This could work nicely with PHP 5.4’s new JsonSerializable interface, Have the trait implement the interface and then every class that uses the trait will implement it as well. THen you can use “json_encode” like you normally would. http://php.net/manual/en/class.jsonserializable.php