I have this class with three variables, one of them being an array. I have written a method that I'll use inside json_encode().
public function getJSONString(){
return [
'id' => $this->id,
'name' => $this->name,
'books' => $this->books
];
}
books is an array of Book objects. Each Book object also has the same exact method but then with its own variables.
public function getJSONString(){
return [
'id' => $this->id,
'title' => $this->title
];
}
When I call print(json_encode($author->getJSONString())) I recieve this:
{"id":"1","name":"name1","books":[{},{}]}
Any idea why books remains empty? Thanks in advance!
$this->booksis empty. Check if it's emptyvar_dump($this->books)and check the code that sets it's value may be it is executing after you calledgetJSONString()print_r()your variable and see.