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:
JSONized.php
1 2 3 4 5 6 7 8 9 10 11 | <?php trait JSONized { public function toJson() { $properties = get_object_vars($this); return json_encode($properties); } } |
User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php class User { use JSONized; public $username; public $password; public $email; public function __construct($username, $password, $email) { $this->username = $username; $this->password = md5($password); $this->email = $email; } } |
test.php
1 2 3 4 5 6 7 | <?php include_once 'JSONized.php'; include_once 'User.php'; $emran = new User('phpfour', 'emran123', 'phpfour@gmail.com'); echo $emran->toJson(); |
The result of running the above code will be like this:
1 2 3 4 5 | { "username" : "phpfour", "password" : "02c2ec1e3f21e97dd5ac747147a141e0", "email" : "phpfour@gmail.com" } |
Pretty cool! ๐
Good post. Tobe vai eta kon account er info? :p
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!
Nice example ๐ Trait is about mixin different roles of a class.
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