【问题标题】:PHP class instance to JSONPHP 类实例转 JSON
【发布时间】: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

标签: php json object encode


【解决方案1】:

你就在那里。结合 json_encode 查看get_object_vars,您将拥有所需的一切。正在做:

json_encode(get_object_vars($error));

应该准确地返回您正在寻找的内容。

cmets 提出 get_object_vars 尊重可见性,因此请考虑在您的班级中执行以下操作:

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

然后将之前的建议改为:

json_encode($error->expose());

这应该解决可见性问题。

【讨论】:

  • 我之前尝试过,但它返回了 {}。猜猜我以前做错了什么,谢谢!
  • AFAIK get_object_vars 也考虑了它被调用的范围,所以如果你从对象内部的方法调用它,你也可以访问私有变量
  • json_encode(get_object_vars($error));将显示公共成员,不显示私人成员。
  • 是的,get_object_vars 尊重可见性,因此您可能需要添加“公开”方法或类似的方法来处理它。我会将此建议添加到答案中。
【解决方案2】:
public function toJSON(){
    $json = array(
        'name' => $this->getName(),
        'code' => $this->getCode(),
        'msg' => $this->getMsg(),
    );

    return json_encode($json);
}

演示:http://codepad.org/mPNGD6Gv

【讨论】:

    【解决方案3】:

    您需要公开您的变量,以便它们出现在json_encode()

    另外,您要查找的代码是

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

    【讨论】:

    • 我喜欢这个,因为我不知道 get_object_vars 排除您不想序列化的属性的方法。
    【解决方案4】:

    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);
        }
    }
    

    然后,您可以使用 json_encode

    将错误对象转换为 JSON
    $error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
    echo json_encode($error);
    

    查看示例here

    More information about \JsonSerializable

    【讨论】:

    • 请注意,类的名称应该是 MyError,因为第二个 code-sn-p 创建了一个新的 MyError 实例,而不是 Error
    【解决方案5】:

    在 Linux 中,以下内容会将给定类条目的值写入文件 ~/.config/scriptname/scriptname.conf,如果文件不存在则创建该文件,否则在加载时读取并设置类值:

    /* 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"];       
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2016-11-16
      • 2015-05-29
      • 2011-12-31
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多