Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP7 return type to JSON

Tags:

php

php-7

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?

like image 241
mpalencia Avatar asked Dec 01 '22 10:12

mpalencia


1 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.

like image 175
KhorneHoly Avatar answered Dec 03 '22 23:12

KhorneHoly