且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 PHP 对象序列化为 JSON

更新时间:2022-12-10 12:35:58


编辑:目前是 2016 年 9 月 24 日,PHP 5.4 已于 2012 年 3 月 1 日发布,支持已于 2015 年 9 月 1 日结束.不过,这个答案似乎获得了赞成票.如果您仍在使用 PHP <5.4、你正在创造安全风险并危及你的项目.如果您没有令人信服的理由保持 = 5.4,不要使用这个答案,而只使用 PHP>= 5.4(或者,你知道,最近的一) 并实现JsonSerializable 接口


edit: it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project. If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer, and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface

您将定义一个函数,例如名为 getJsonData();,它将返回一个数组、stdClass 对象或其他一些具有可见参数的对象,而不是返回私有/受保护的,并执行 json_encode($data->getJsonData());.本质上是实现5.4的功能,只是手动调用.

You would define a function, for instance named getJsonData();, which would return either an array, stdClass object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData());. In essence, implement the function from 5.4, but call it by hand.

这样的事情会起作用,因为 get_object_vars() 从类内部调用,可以访问私有/受保护的变量:

Something like this would work, as get_object_vars() is called from inside the class, having access to private/protected variables:

function getJsonData(){
    $var = get_object_vars($this);
    foreach ($var as &$value) {
        if (is_object($value) && method_exists($value,'getJsonData')) {
            $value = $value->getJsonData();
        }
    }
    return $var;
}