PHP类实例到JSON [英] PHP class instance to JSON

查看:107
本文介绍了PHP类实例到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以JSON格式回显对象的内容.我对PHP完全没有经验,我想知道是否有预定义的函数来执行此操作(例如json_encode()),还是您必须自己构建字符串? 当谷歌搜索"PHP对象到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);
    }
}

我想要JSON返回的内容:

What I want toJSON to return:

{name:"$ name var的内容",代码:1001,msg:时出错 做请求}

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

推荐答案

您就在那里.结合json_encode一起查看 get_object_vars ,您将拥有所需的一切.正在执行:

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.

这些注释唤起了get_object_vars对可见性的尊重,因此请考虑在您的课程中执行以下操作:

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.

这篇关于PHP类实例到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆