Created
January 15, 2011 08:36
-
-
Save Nutrox/780784 to your computer and use it in GitHub Desktop.
PHP - JSONObject class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JSONObject extends stdClass { | |
// Accepts an array, object, or JSON encoded string. | |
public function __construct( $o=null ) { | |
if( $o === null ) { | |
return; | |
} | |
if( is_string( $o ) ) { | |
$o = json_decode( $o ); | |
} | |
if( is_object( $o ) || is_array( $o ) ) { | |
$this->cast( $o ); | |
} | |
} | |
// When this object is cast to a string, a JSON encoded string is returned. | |
public function __toString() { | |
return json_encode( $this ); | |
} | |
// Returns NULL when an unset property is accessed. | |
public function __get( $name ) { | |
if( isset( $this->$name ) ) { | |
return $this->$name; | |
} | |
return null; | |
} | |
// For internal use, maps/casts an array or object to this object. | |
private function cast( $o ) { | |
foreach( $o as $k => $v ) { | |
if( is_object( $v ) ) { | |
$this->$k = new JSONObject( $v ); | |
continue; | |
} | |
$this->$k = $v; | |
} | |
} | |
} | |
// BASIC EXAMPLE OF USE // | |
$o1 = new JSONObject(); | |
$o1->apple = 'green'; | |
$o1->banana = 'yellow'; | |
echo $o1; // output: {"apple":"green","banana":"yellow"} | |
$o2 = new JSONObject( '{"apple":"green","banana":"yellow"}' ); | |
echo $o2->apple; // output: green | |
echo $o2->banana; // output: yellow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment