PHP Json encode returns empty for an object

Thudani Hettimulla :

I have a php class like,

<?php

namespace app\test;

class TestObject
{
    private $obj_id;
    private $obj_name;

    public function __construct($obj_id, $obj_name)
    {
        $this->obj_id = $obj_id;
        $this->obj_name = $obj_name;
    }

    public function get_obj_id()
    {
        return $this->obj_id;
    }

    public function get_obj_name()
    {
        return $this->obj_name;
    }
}

And in my index.php I am trying to create a TestObject and json encode it with,

$obj_1 = new TestObject(1, "testname");
echo json_encode($obj_1);

But as output I get only {} Any idea, why it is not showing object fields?

ADyson :

"why it is not showing object fields"

...because they are marked private. As soon as they are marked public they will be visible to json_encode().

class TestObject
{
    public $obj_id;
    public $obj_name;

    public function __construct($obj_id, $obj_name)
    {
        $this->obj_id = $obj_id;
        $this->obj_name = $obj_name;
    }

    public function get_obj_id()
    {
        return $this->obj_id;
    }

    public function get_obj_name()
    {
        return $this->obj_name;
    }
}

$obj_1 = new TestObject(1, "testname");
echo json_encode($obj_1);

Output:

{"obj_id":1,"obj_name":"testname"}

Demo: http://sandbox.onlinephpfunctions.com/code/528d3b495cd23c9ffbea424556cd042c486c413c

Alternatively if you need to keep the properties private and still JSON-encode them, there are various techniques you can employ - see PHP json_encode class private members for details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198395&siteId=1