Skip to content

Instantly share code, notes, and snippets.

@NotLazy
Last active August 30, 2022 14:35
Show Gist options
  • Save NotLazy/c52c39a718768733f71b3e815d252073 to your computer and use it in GitHub Desktop.
Save NotLazy/c52c39a718768733f71b3e815d252073 to your computer and use it in GitHub Desktop.
PHP 8.1 Workaround for json_decode deprecating null
<?php
// If you're anything like me, you upgraded from PHP 7.x to PHP 8.x and discovered that everywhere you were using
// JSON in your code, there were some new deprecation warnings getting in your way.
//
// So, since I use auto_prepend_file in my php.ini, this was a super easy solution.
// My recommendation is to do the same thing. Create an auto_prepend file, and put this snippet in it.
// the new function
define("decode", "json_decode");
define("encode", "json_encode");
function json($action, $object, $pretty=false){
if($object == NULL) return NULL;
if($action == decode){
return json_decode($object, true);
}elseif($action == encode){
if($pretty){
return json(encode, $object, JSON_PRETTY_PRINT);
}else{
return json(encode, $object);
}
}else{
throw new Exception("Invalid action provided to json()");
}
}
// end the new function
// usage
$json = json(encode, ["myObject" => "is not an Object ;)"]); // {"myObject": "is not an Object ;)"}
$decoded = json(decode, $json); // Array([myObject] => "is not an Object ;)")
json(encode, NULL); // null, with no deprecation warning.
// and finally,
json(encode, $decoded, true);
// Returns:
// {
// "myObject": "is not an Object ;)"
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment