Symfony 2/PHP:json_encode [英] Symfony 2 / Php : json_encode

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

问题描述

一段时间以来,我一直在寻找解决问题的方法,但没有成功,所以我在这里问.

I've been looking to a solution to my problem for a while without success so I'm asking here.

我们如何在包含私有属性的对象(或只是一个对象)数组上返回json编码的结果?

How can we return a json-encoded result on an array of objects (or just an object) containing private properties ?

实际上,当您使用json_encode($ myObject)时,它不会显示私有或受保护的属性,这些属性在使用Symfony时在模型中随处可见...

Indeed, when you use json_encode($myObject), it won't display the private or protected properties, which are present everywhere in the model when using Symfony...

令我惊讶的是,我找不到像json_encode这样的方法来调用getter而不是属性本身.

I'm surprised I couldn't find any method like json_encode that would call getters instead of properties themselves.

有什么主意吗?

编辑

在那种情况下,我宁愿做一个看起来像这样的独特功能:

In that case I would rather do a unique function that looks like :

public function toArray() {
    $vars = get_object_vars($this);
    $result = array();
    foreach ($vars as $key => $value) {
        if (is_object($value)) {
            $result[$key] = toArray($value);
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

为了避免每次都重写每个属性名称...

in order to avoid rewriting every property name everytime...

但是无论如何,我认为我只会创建一个包含所需变量的数组,这样我就不会碰到模型(生成的代码).

But anyway I think I'll just create an array containing the vars I need, so that I won't touch the model (which is generated code).

推荐答案

现在没有办法.只有php serialize/unserialize才能处理对象的真实序列化.

Right now there is no way for this. Only php serialize/unserialize handles the true serialisation of objects.

您必须自己实现它们,或者让对象自己返回json值.

You'll have to implement them yourselve, or rather let objects return their json values themselves.

您将必须实现自己的方法toArray(),在其中将数组中的所有私有值公开:

You will have to implement your own method toArray() where you expose all your private values in an array:

public function toArray()
{
  return array(
      'property1' => $this->myproperty1,
      'property2' => $this->myproperty2
  );
}

并这样称呼它:

json_encode(MyObject->toArray());

[",该问题与教义无关,但是由于您同时提到了symfony2和模型,因此可以考虑对模型使用数组水合:

[ this question is not about doctrine, but since you mention both symfony2 and the model, you can consider using Array Hydration for your model: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#array-hydration ]

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

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