Skip to content

Instantly share code, notes, and snippets.

@gsdevme
Created July 7, 2012 13:29
Show Gist options
  • Save gsdevme/3066490 to your computer and use it in GitHub Desktop.
Save gsdevme/3066490 to your computer and use it in GitHub Desktop.
Creates a fallback for those not using PHP 5.4, however requires you use jsonEncode() not json_encode
<?php
if (PHP_VERSION >= 50400) {
function jsonEncode(){
return call_user_func_array('json_encode', (array)func_get_args());
}
}else{
interface JsonSerializable{
public function jsonSerialize();
}
function jsonEncode(){
$args = func_get_args();
if(count($args) > 0){
if(!is_object($args[0])){
return call_user_func_array('json_encode', (array)func_get_args());
}
try{
$value = array_shift($args);
$class = new ReflectionClass($value);
if($class->implementsInterface('JsonSerializable')){
array_unshift($args, $value->jsonSerialize());
return call_user_func_array('json_encode', $args);
}
}catch(Exception $e){
}
}
if(function_exists('json_last_error')){
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
throw new RuntimeException('Maximum stack depth exceeded', null, ((isset($e) ? $e : null)));
case JSON_ERROR_STATE_MISMATCH:
throw new RuntimeException('Underflow or the modes mismatch', null, ((isset($e) ? $e : null)));
case JSON_ERROR_CTRL_CHAR:
throw new RuntimeException('Unexpected control character found', null, ((isset($e) ? $e : null)));
case JSON_ERROR_SYNTAX:
throw new RuntimeException('Syntax error, malformed JSON', null, ((isset($e) ? $e : null)));
case JSON_ERROR_UTF8:
throw new RuntimeException('Malformed UTF-8 characters, possibly incorrectly encoded', null, ((isset($e) ? $e : null)));
default:
throw new RuntimeException('Unknown Error', null, ((isset($e) ? $e : null)));
}
}
throw new RuntimeException('Your JSON is fucked, no json_last_error() either...');
}
}
class Piss implements JsonSerializable
{
private $_bullshit;
private $_moreBullshit;
public function __construct()
{
$this->_bullshit = range(1,10);
}
public function jsonSerialize()
{
return $this->_bullshit;
}
}
echo jsonEncode(array('a' => 1));
echo jsonEncode(new Piss());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment