Created
March 31, 2012 15:56
-
-
Save phpfour/2266371 to your computer and use it in GitHub Desktop.
A PHP trait to add a simple toJson function to your classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait JSONized { | |
public function toJson() | |
{ | |
$properties = get_object_vars($this); | |
return json_encode($properties); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include_once 'JSONized.php'; | |
include_once 'User.php'; | |
$emran = new User('phpfour', 'emran123', 'phpfour@gmail.com'); | |
echo $emran->toJson(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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