Last Updated: February 25, 2016
·
823
· abimaelmartell

PHP Object JSON representation

<?php
class Comment implements jsonSerializable{
    public $author;
    public $content;
    public $date;

    public function jsonSerialize(){
        return array(
            "author" => $this->author,
            "content" => $this->content,
            "date" => $this->date
        );
    }
}
$myComment = new Comment();
$myComment->author = "Abimael Martell";
$myComment->content = "Hi there";
$myComment->date = "2012-11-13 21:06:12";
echo json_encode($myComment);
//{
//    "author":"Abimael Martell",
//    "content":"Hi there",
//    "date":"2012-11-13 21:06:12"
//}
?>