Home » Php » php – Is it allowed to set return to json in documentation?

php – Is it allowed to set return to json in documentation?

Posted by: admin July 12, 2020 Leave a comment

Questions:

So, while documenting a php code I’m writing, I stopped where I usually said @return string The json output, on functions that I actually returned json.

So, I was wondering if it is right to set

*
* @return json
*/
public function test()
{
    $test = array('hola' => array('en' => 'hello', 'ro' => 'salut'));
    return json_encode($test);
}

instead of

*
* @return string
*/
public function test()
{
    $test = array('hola' => array('en' => 'hello', 'ro' => 'salut'));
    return json_encode($test);
}

I searched for related question, and overlooked manuals, but non that I have seen, had mentioned my doubt.

http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.return.pkg.html

Update

Just as a reference, of where I got all this started. I saw a couple of times, the following:

*
* @return View
*/

So, I guess that is a proper return?

How to&Answers:

json” is not a primitive type in PHP, or in fact any type. You need to document returned types, not what the content of these types mean. If you specify json as return “type”, this implies an object of class json, because json has no other meaning in PHP.

You can only document it as returning a string.

Answer:

As orangepill commented, you should use the type string and add JSON in the description.

@return string JSON

PHPDoc Manual

@return datatype description
@return datatype1|datatype2 description

In reference to the datatype, the manual states

The datatype should be a valid PHP type (int, string, bool, etc), a
class name for the type of object returned, or simply “mixed”. If you
want to explicitly show multiple possible return types, list them
pipe-delimited without spaces (e.g. “@return int|string”)

Answer:

I would prefer to see a return type of json. It’s true that you are returning json in the form of a string, however json is more specific, and lets others know what to expect.