【发布时间】:2012-04-11 09:08:23
【问题描述】:
我正在尝试以 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);
}
}
我希望 toJSON 返回的内容:
{ name: "$name var 的内容", code : 1001, msg : error while 做请求}
【问题讨论】:
-
写这篇文章的时候还没有问题,但是如果你现在使用 >5.4,你可以让你的类实现JsonSerializable