safe icon indicating copy to clipboard operation
safe copied to clipboard

Improve the signature of `json_decode` function

Open aturki opened this issue 2 years ago • 2 comments

The native json_decode function returns:

  • null in case of an error
  • an stdClass if the $assoc parameter is false
  • an associative array if it's true

Since the safe implementation throws by default, the null value ia never returned. I thin we can improve the phpdoc return type of this function so that the return type is deduced depending on the value of $assoc parameter so that we can leverage better type checking using phpstan (https://phpstan.org/blog/phpstan-1-6-0-with-conditional-return-types)

aturki avatar Mar 08 '23 08:03 aturki

Actually json_decode can return a null value, if you decode the null string:

$ php -r "var_dump(json_decode('null'));"
Command line code:1:
NULL

cedric-anne avatar May 13 '25 20:05 cedric-anne

JSON isn't just arrays and objects. null, 1, 1.25, true, false, "string" - are all valid JSON values, so the function may return null|int|float|bool|string|array|stdClass even in case of valid JSON

oprypkhantc avatar May 28 '25 15:05 oprypkhantc