Reinard
Reinard

Reputation: 3654

PHP class instance to JSON

I'm trying echo the contents of an object in a JSON format. I'm quite unexperienced with PHP and I was wondering if there is a predefined function to do this (like json_encode()) or do you have to build the string yourself? When Googling "PHP object to JSON", I'm just finding garbage.

class Error {
    private $name;
    private $code;
    private $msg;
    public function __construct($ErrorName, $ErrorCode, $ErrorMSG){
        $this->name = $ErrorName;
        $this->code = $ErrorCode;
        $this->msg = $ErrorMSG;
    }
    public function getCode(){
        return $this->code;
    }
    public function getName(){
        return $this->name;
    }
    public function getMsg(){
        return $this->msg;
    }
    public function toJSON(){
        $json = "";

        return json_encode($json);
    }
}

What I want toJSON to return:

{ name: "the content of $name var", code : 1001, msg : error while doing request}

Upvotes: 47

Views: 71516

Answers (5)

NVRM
NVRM

Reputation: 13077

In Linux, the following will write the value of a given class entry in a file ~/.config/scriptname/scriptname.conf, create the file if it doesn't exist, and otherwise read and set back the class value at loading:

/* Example class */
class flag {
  static $COLORSET = ["\033[34;1m","\033[31;1m"];
}
/* Retrieve and set back values, otherwise create config file with the defined value --------------------------------------------------*/
if (!is_file($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf")){
    @mkdir($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]);
    @file_put_contents($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf",json_encode(["COLORSET"=>flag::$COLORSET]));
} else {
    flag::$COLORSET = json_decode(file_get_contents($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf"), true)["COLORSET"];       
}

Upvotes: 0

Mandy Schoep
Mandy Schoep

Reputation: 981

An alternative solution in PHP 5.4+ is using the JsonSerializable interface.

class Error implements \JsonSerializable
{
    private $name;
    private $code;
    private $msg;

    public function __construct($errorName, $errorCode, $errorMSG)
    {
        $this->name = $errorName;
        $this->code = $errorCode;
        $this->msg = $errorMSG;
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

Then, you can convert your error object to JSON with json_encode

$error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
echo json_encode($error);

Check out the example here

More information about \JsonSerializable

Upvotes: 48

clexmond
clexmond

Reputation: 1549

You're just about there. Take a look at get_object_vars in combination with json_encode and you'll have everything you need. Doing:

json_encode(get_object_vars($error));

should return exactly what you're looking for.

The comments brought up get_object_vars respect for visibility, so consider doing something like the following in your class:

public function expose() {
    return get_object_vars($this);
}

And then changing the previous suggestion to:

json_encode($error->expose());

That should take care of visibility issues.

Upvotes: 54

Naftali
Naftali

Reputation: 146302

public function toJSON(){
    $json = array(
        'name' => $this->getName(),
        'code' => $this->getCode(),
        'msg' => $this->getMsg(),
    );

    return json_encode($json);
}

Demo: http://codepad.org/mPNGD6Gv

Upvotes: 7

Madara's Ghost
Madara's Ghost

Reputation: 174957

You'll need to make your variable public, in order for them to appear on json_encode().

Also, the code you're looking for is

public function toJSON(){
    return json_encode($this);
}

Upvotes: 11

Related Questions