-2

I have a User object and I want to encode it to a JSON format, but json_encode() returns an empty value "{}". What I am doing wrong?

Here's my code:

<?php
header('Content-Type: application/json');
require_once 'DataBase.php';
include_once '../Model/User.php';
$user = DataBase::getUser('username', $_GET['q']); //getting User object
$json = json_encode($user); //returns "{}"
echo $json;
APerson
  • 8,140
  • 8
  • 35
  • 49
koryakinp
  • 3,989
  • 6
  • 26
  • 56

2 Answers2

1

I found a solution. The properties of the User object were private. All I need is to created to_json() method in a User class.

koryakinp
  • 3,989
  • 6
  • 26
  • 56
  • You should accept your own answer when you're able to and unmark the other answer as accepted - since the other answer didn't solve your problem at all. – sjagr Nov 10 '14 at 19:25
  • I was able to slove my problem, only because Roman Sokolovskyy has provided a link to a similar issue. Should I mark both answers ? – koryakinp Nov 10 '14 at 20:03
-3

I think because $user = DataBase::getUser('username', $_GET['q']); returns an object, not array

Using json_encode on objects in PHP (regardless of scope)

Community
  • 1
  • 1