I'm trying to encode some properties in a class in php to JSON but all my method is returning is {}
Here's my code, where am I going wrong?
Thanks.
<?php
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
$json = new stdClass;
foreach (get_object_vars($this) as $name => $value) {
$this->$name = $value;
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman@gmail.com");
print_r( $person1->getJsonData() );
That's is because you are not using the $json variable but instead you are using $this->$name. Which $this are you refering too? You aren't using the $json variable from what I am seeing.
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
//I'd make this an array
//$json = new stdClass;
$json = array();
foreach (get_object_vars($this) as $name => $value) {
//Here is my change
//$this->$name = $value;
$json[$name] = $value
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman@gmail.com");
print_r( $person1->getJsonData() );
Hope it solves you problem. That's how I would do it.
Implement the JsonSerializable interface in your class, starting with PHP 5.4.