• Date: March 3, 2012
  • Author: Slawek Lukasiewicz
  • Comments: No Comments
  • Category: PHP

1 March PHP 5.4 was released. 5.4 version introduces a lot of interesting features and improvements.

I will show some of them – the most interesting for me – in separate blog notes. I will start from JSON extension.

Using json_encode with objects, JsonSerializable interface

By default, when we pass object to json_encode function, it will return JSON representation of object public properties.

class ClassToSerialize 
{
        public $a=2;
        private $b=4;
}
 
$classToSerializeInstance = new ClassToSerialize();
print json_encode($classToSerializeInstance);
# {"a":2}

PHP 5.4 introduces JsonSerializable interface with JsonSerialize abstract method. After implementing this method we can independently set values used in JSON representation.

class ClassToSerialize implements JsonSerializable
{
        public $a=2;
        private $b=4;
        public function JsonSerialize() {
                return array('a'=>$this->a, 'b'=>$this->b, 'c'=>3);
        }
}
 
$classToSerializeInstance = new ClassToSerialize();
print json_encode($classToSerializeInstance);
# {"a":2,"b":4,"c":3}

Some new json_encode function options

JSON_UNESCAPED_SLASHES
By default json_encode escapes slashes with backslash. In some circumstances this behaviour can be really annoying. We can disable it using JSON_UNESCAPED_SLASHES option.

JSON_PRETTY_PRINT
Output of json_encode is absolutely not suitable for human. Using JSON_PRETTY_PRINT we can get JSON representation in readable form.

Pretty output example

{
    "first": [
        "one",
        "two",
        "three"
    ],
    "second": {
        "fruits": [
            "apple",
            "orange"
        ]
    }
}

 

JSON_UNESCAPED_UNICODE
This option is connected with this request, and in some cases can be useful.

No Comments Yet

Leave a Reply →