Home  • Programming • PHP

How to PHP class instance to JSON having private properties?

<?php
class Book implements JsonSerializable{
	
	private $id;
	private $title;
	private $author;
	
	function __construct($_id,$_title,$_author){
		$this->id=$_id;
		$this->title=$_title;
		$this->author=$_author;
	}
	
	public function jsonSerialize()
    {
        return get_object_vars($this);
    }
	
	public function toJSON(){
       return json_encode($this);
    }
	
}

	$obj=new Book(3,"Introduction PHP","Towhid");
	echo $obj->toJSON();
	//echo json_encode($obj);

?>

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd