Skip to content

Instantly share code, notes, and snippets.

@phpfour
Created March 31, 2012 15:56
Show Gist options
  • Save phpfour/2266371 to your computer and use it in GitHub Desktop.
Save phpfour/2266371 to your computer and use it in GitHub Desktop.
A PHP trait to add a simple toJson function to your classes.
<?php
trait JSONized {
public function toJson()
{
$properties = get_object_vars($this);
return json_encode($properties);
}
}
<?php
include_once 'JSONized.php';
include_once 'User.php';
$emran = new User('phpfour', 'emran123', 'phpfour@gmail.com');
echo $emran->toJson();
<?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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment