PHP7 return type to JSON

Viewed 4564

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?

3 Answers

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.

class PropertyNormalizer
{
    /**
     * @param Object $doc
     * @return NormalisedProperty
     */
    public function normalize(Object $doc): Object
    {
        $property = new NormalisedProperty($doc);
        // ... 
        return $property;
    }
}

I like @KhorneHoly answer. However, you might consider a better function name (myFunction is just a dummy name, isn't it?):

function getJson($a) : string { }

This makes it obvious that returned string is actually JSON (with no need to use PHPDocs).

Related