-1

I have two classes ServiceDetails and AvailableServices

class ServiceDetails {
    private $service_name;
    private $price;
    private $currency_id;
    public function __construct($service_name, $price, $currency_id) {
        $this->service_name = $service_name;
        $this->price = $price;
        $this->currency_id = $currency_id;
    }
}

class AvailableServices {
    public $services;
    public function __construct() {
        $this->services = [];
    }
}

I created an instance of AvailableServices and added an object of class ServiceDetails into the $services array of the AvailableServices instance.

$services = new AvailableServices();
$service_details = new ServiceDetails($a, $b, $c);
$services->services[] = clone $service_details;

I var_dump the $services object and it outputs correctly. However, when I do json_encode, nothing outputs except the services property of AvailableServices.

var_dump($services); // something
echo json_encode($services); // nothing
Jenz
  • 8,280
  • 7
  • 44
  • 77
dayuloli
  • 16,205
  • 16
  • 71
  • 126

2 Answers2

1

Correct answer here is to implement JsonSerializable interface for ServiceDetails class.

class ServiceDetails implements JsonSerializable{
    private $service_name;
    private $price;
    private $currency_id;
    public function __construct($service_name, $price, $currency_id) {
        $this->service_name = $service_name;
        $this->price = $price;
        $this->currency_id = $currency_id;
    }

    /**
     * Returns JSON representation
     * 
     * @return array|mixed
     */
    public function jsonSerialize() {
        return get_object_vars($this);
    }    
}
lisachenko
  • 5,952
  • 3
  • 31
  • 51
  • There isn't really a 'correct' method. It depends on what you're looking for. My answer isn't wrong per se. See http://stackoverflow.com/q/804045/2317532 – dayuloli Nov 03 '14 at 07:31
-1

For json_encode to print out properties, those properties must be public. Changing the ServiceDetails to use public instead of private resolved the issue.

class ServiceDetails {
    public $service_name;
    public $price;
    public $currency_id;
    public function __construct($service_name, $price, $currency_id) {
        $this->service_name = $service_name;
        $this->price = $price;
        $this->currency_id = $currency_id;
    }
}
dayuloli
  • 16,205
  • 16
  • 71
  • 126