PHP 类实例转 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9896254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP class instance to JSON
提问by Reinard
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.
我正在尝试以 JSON 格式回显对象的内容。我对 PHP 非常缺乏经验,我想知道是否有一个预定义的函数来执行此操作(例如 json_encode()),还是您必须自己构建字符串?当谷歌搜索“PHP 对象到 JSON”时,我只是发现垃圾。
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:
我想要JSON返回的内容:
{ name: "the content of $name var", code : 1001, msg : error while doing request}
{名称:“$name var 的内容”,代码:1001,味精:执行请求时出错}
回答by clexmond
You're just about there. Take a look at get_object_varsin combination with json_encode and you'll have everything you need. Doing:
你就在那里。将get_object_vars与 json_encode 结合使用,您将拥有所需的一切。正在做:
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:
评论提出了 get_object_vars 对可见性的尊重,因此请考虑在您的班级中执行以下操作:
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.
这应该解决可见性问题。
回答by Mandy Schoep
An alternative solution in PHP 5.4+is using the JsonSerializableinterface.
PHP 5.4+ 中的另一种解决方案是使用JsonSerializable接口。
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 JSONwith json_encode
然后,您可以使用json_encode将错误对象转换为JSON
$error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
echo json_encode($error);
Check out the example here
在这里查看示例
回答by Madara's Ghost
You'll need to make your variable public, in order for them to appear on json_encode()
.
您需要公开您的变量,以便它们出现在json_encode()
.
Also, the code you're looking for is
此外,您正在寻找的代码是
public function toJSON(){
return json_encode($this);
}
回答by Naftali aka Neal
public function toJSON(){
$json = array(
'name' => $this->getName(),
'code' => $this->getCode(),
'msg' => $this->getMsg(),
);
return json_encode($json);
}
回答by NVRM
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:
在 Linux 中,以下代码会将给定类条目的值写入文件~/.config/scriptname/scriptname.conf
,如果文件不存在则创建该文件,否则在加载时读取并设置类值:
/* Example class */
class flag {
static $COLORSET = ["3[34;1m","3[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"];
}