Reputation: 201
hi guys i got a problem . while i was implementing some code i reached the point that i need to use toJson method in each object
so inside the class i have added this code
public function toJson(){
return json_encode($this); // $this which refers to the current object
}
it has returned just {}
so i knew that it does not recognize the properties of this class
so instead i have tried to convert it like that
public function toJson(){
$array=(array)$this;
return json_encode($array);
}
i got weird result
string '{"\u0000Response\u0000status":0,"\u0000Response\u0000data":null,"\u0000Response\u0000error":" type non valide "}' (length=112)
i could eventually write customized json object
like this
public function toJson(){
$myjson="{field1:data1,field2:data2}";
return $myjson;
}
but i do not want to return back to it each time that i add new property
i appreciate if you have any idea about why converting this does not work
Upvotes: 0
Views: 53
Reputation: 6017
This usage works for me with primitives, arrays, associate arrays, and objects:
<?php
class Test {
var $a = "1";
var $b = array(3, 5, "cat", "monkey");
var $c = array("animal" => "dromedary");
public function toJson() {
return json_encode($this);
}
}
$test = new Test();
$test->d = new Test();
echo $test->toJson();
?>
Running it results in the expected JSON output:
$ php test.php
{"a":"1","b":[3,5,"cat","monkey"],"c":{"animal":"dromedary"},"d":{"a":"1","b":[3,5,"cat","monkey"],"c": {"animal":"dromedary"}}}
I'm still running PHP 5.3.15.
Upvotes: 1
Reputation: 76240
You need to convert the object properties to array before encoding to JSON:
public function toJson(){
return json_encode(get_object_vars($this));
}
As you can see, you can use get_object_vars to accomplish that.
Upvotes: 1