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<?php 3 4trait JSONized { 5 6 public function toJson() 7 { 8 $properties = get_object_vars($this); 9 return json_encode($properties);10 }11 12}
User.php
1<?php 2 3class User 4{ 5 use JSONized; 6 7 public $username; 8 public $password; 9 public $email;10 11 public function __construct($username, $password, $email)12 {13 $this->username = $username;14 $this->password = md5($password);15 $this->email = $email;16 }17}
test.php
1<?php2 3include_once 'JSONized.php';4include_once 'User.php';5 6$emran = new User('phpfour', 'emran123', 'phpfour@gmail.com');7echo $emran->toJson();
The result of running the above code will be like this:
1{2 "username" : "phpfour",3 "password" : "02c2ec1e3f21e97dd5ac747147a141e0",4 "email" : "phpfour@gmail.com"5}