Skip to content

Instantly share code, notes, and snippets.

@lionrajkumar
Created December 21, 2023 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lionrajkumar/56d62245161440ee05173942ea03b366 to your computer and use it in GitHub Desktop.
Save lionrajkumar/56d62245161440ee05173942ea03b366 to your computer and use it in GitHub Desktop.
Converting JSON String to PHP class

Converting JSON String to PHP class

class JSONObject {
    public function __construct($json = false) {
        if ($json) $this->set(json_decode($json, true));
    }

    public function set($data) {
        foreach ($data AS $key => $value) {
            if (is_array($value)) {
                $sub = new JSONObject;
                $sub->set($value);
                $value = $sub;
            }
            $this->{$key} = $value;
        }
    }
}

// These next steps aren't necessary. I'm just prepping test data.
$data = array(
    "this" => "that",
    "what" => "who",
    "how" => "dy",
    "multi" => array(
        "more" => "stuff"
    )
);
$jsonString = json_encode($data);

// Here's the sweetness.
$class = new JSONObject($jsonString);
print_r($class);

Ref: Michael McTiernan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment