Search code examples
phpphp-7

PHP7 return type to JSON


PHP 7 has a new feature which is a return type declaration.

We can return type a 'string' like:

function myFunction ($a) : string  { }

We can also return type an 'array' like:

function myFunction ($a) : array  { }

But how can we declare a 'JSON' type of response?


Solution

  • JSON isn't a native datatype in PHP, it's a structured string. So if your function returns JSON, you're returning a string.

    So function myFunction ($a) : string { } would be correct.

    If you want to describe the return further you should be using docs.

    /**
     * @return string $jsonString The returned string contains JSON
     */
    function myFunction ($a) : string  { }
    

    The same also goes for serialized objects in PHP. A serialized object is a structured string.