user3022069
user3022069

Reputation: 397

Encoding static member of class as JSON in PHP

I have the following piece of code.

class SomeClass
{
    public static $one = 1;
    private static $two = 2;
    public $three = 3;
    private $four = 4;
}

header("Content-Type: application/json");
echo json_encode(new SomeClass());

What I want to achieve is encode the public class property and member as a JSON object. My problem is that json_encode() ignores public static $one = 1; and the result will be:

{
    "three": ​3
}

Although I expect it to print the public static member as well, such as:

{
    "one": 1,
    "three": ​3
}

Can JSON encoding be done with static members in PHP?

Upvotes: 2

Views: 1012

Answers (2)

Kevin Kopf
Kevin Kopf

Reputation: 14210

According to PHP manual:

Static properties cannot be accessed through the object using the arrow operator ->.

That means no

Nevertheless, I came up with the solution utilizing Reflections:

class SomeClass
{
    public static $one = 1;
    private static $two = 2;
    public $three = 3;
    private $four = 4;
}

$reflection = new ReflectionClass('SomeClass');
$instance = $reflection->newInstance();
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);

$jsonArray = array();

foreach($properties as $property) {
    $jsonArray[$property->getName()] = $property->getValue($instance);
}

echo json_encode($jsonArray);

The result is

{"one":1,"three":3}

Upvotes: 2

sergio
sergio

Reputation: 5260

In native implementation: NO.

In case you use Php v >= 5.4.0, you can use JsonSerializable

Here is example:

class myClass implements JsonSerializable
{
    private $_name = 'test_name';
    public $email = '[email protected]';
    public static $staticVar = 5;

    public function jsonSerialize()
    {
        return get_class_vars(get_class($this));
    }
}

echo json_encode(new myClass());

Upvotes: 2

Related Questions