扩展嵌套对象的json_encode

时间:2012-10-08 16:43:35

标签: php object json

我正在使用 PHP 5.2.x ,并希望仅使用私有成员对自定义PHP类的对象进行编码。其中一个私有成员是另一个自定义类的对象数组。

我尝试了https://stackoverflow.com/a/7005915/17716中概述的解决方案,但显然无法递归工作。我能看到的唯一解决方案是以某种方式扩展json_encode方法,以便调用类的json_encode方法版本而不是默认方法。

供参考,代码如下:

Class A {
    private $x;
    private $y;
    private $z;
    private $xy;
    private $yz;
    private $zx;

    public function f1() {
        ...
    }

    public function f2() {
        ...
    }
    .
    .
    .
    public function getJSONEncode() {
         return json_encode(get_object_vars($this));
    }
}

class B {

    private $p; //This finally stores objects of class A
    private $q;
    private $r;

    public function __construct() {
            $this->p = array();
    }

    public function fn1() {
        ...
    }

    public function fn2() {
        ...
    }

    .
    .
    .

    public function getJSONEncode() {
         return json_encode(get_object_vars($this));
    }

}

class C {

    private $arr;

    public function __construct() {
            $this->arr = array();
    }

    public function fillData($data) {
        $obj = new B();
        //create objects of class B and fill in values for all variables
        array_push($this->arr, $obj)
    }

    public function returnData() {
          echo $this->arr[0]->getJSONEncode(); //Edited to add

    }

}

实现这种嵌套json编码的最佳方法是什么?

编辑添加:

执行returnData方法时得到的输出是:

{"p":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}],"q":"Lorem Ipsum","r":"Dolor Sit Amet"}

1 个答案:

答案 0 :(得分:1)

虽然我相信你最好为你的每个类编写一个合适的导出/编码函数(它会为私有和公共值构建一个公共对象只是为了编码 - 你可能会非常聪明并且使用php的reflection能力) - 相反 - 您可以使用以下代码:

/// example class B
class TestB {
  private $value = 123;
}

/// example class A
class TestA {
  private $prop;
  public function __construct(){
    $this->prop = new TestB();
  }
}

function json_encode_private($obj){
  /// export the variable to find the privates
  $exp = var_export($obj, true);
  /// get rid of the __set_state that only works 5.1+
  $exp = preg_replace('/[a-z0-9_]+\:\:__set_state\(/i','((object)', $exp);
  /// rebuild the object
  eval('$enc = json_encode('.$exp.');');
  /// return the encoded value
  return $enc;
}

echo json_encode_private(new TestA());

/// {"prop":{"value":123}}

所以上面应该可行,但我不建议在php的任何地方使用eval - 因为我总是在远处悄悄听到警报铃声:)

更新

只是想到了什么可能会让这更安全,而不是使用eval你可以使用create_function来限制它的某些创造力,或者至少是这些权力的范围。 ..

function json_encode_private($obj){
  $exp = var_export($obj, true);
  $exp = preg_replace('/[a-z0-9_]+\:\:__set_state\(/i','((object)', $exp);
  $enc = create_function('','return json_encode('.$exp.');');
  return $enc();
}

更新2

有机会使用另一种方法将具有私有属性的对象转换为具有公共属性的对象 - 仅使用简单的函数(并且没有评估)。以下内容需要在您使用的任何版本的PHP上进行测试,因为它的行为 - 再次 - 可能不可靠......由于奇怪的\0 Class Name 已转换的私有属性中的\0前缀(请参阅代码中的注释)

有关此奇怪的前缀行为的更多信息:
http://uk3.php.net/language.types.array.php#language.types.array.casting

无论如何,所以使用测试类:

class RandomClass {
  private $var = 123;
  private $obj;
  public function __construct(){
    $this->obj = (object) null;
    $this->obj->time = time();
  }
}

我们可以使用以下函数将其转换为公共对象:

function private_to_public( $a ){
  /// grab our class, convert our object to array, build our return obj
  $c = get_class( $a ); $b = (array) $a; $d = (object) null;
  /// step each property in the array and move over to the object
  /// usually this would be as simple as casting to an object, however
  /// my version of php (5.3) seems to do strange things to private 
  /// properties when casting to an array... hence the code below:
  foreach( $b as $k => $v ){
    /// for some reason private methods are prefixed with a \0 character
    /// and then the classname, followed by \0 before the actual key value. 
    /// This must be some kind of internal protection causing private  
    /// properties to be ignored. \0 is used by some languges to terminate  
    /// strings (not php though, as far as i'm aware).
    if ( ord($k{0}) === 0 ) {
      /// trim off the prefixed weirdnesss..?!
      $e = substr($k, 1 + strlen($c) + 1);
      /// unset the $k var first because it will remember the \0 even 
      /// if other values are assigned to it later on....?!
      unset($k); $k = $e;
    }
    /// so if we have a key, either public or private - set our value on
    /// the destination object.
    if ( $k !== '' && $k !== NULL && $k !== FALSE )  {
      $d->{$k} = $v;
    }
  }
  return $d;
}

所以如果我们把它们放在一起:

$a = new RandomClass();

echo json_encode( private_to_public( $a ) );

/// {"var":123,"obj":{"time":1349777323}}

同样,您最好/最可靠的选择是为每个类定制代码转换方法,或使用Class Reflection创建某种通用解决方案,但后者涉及的更多,涉及的内容比StackOverflow更多......至少我有空的时间;)

更多信息

上述代码在尝试从任何地方访问对象时都会起作用,实现这一点的原因是因为我的第一次尝试显然是使用以下内容:

echo json_encode( get_object_vars($a) );

/// you will get {} which isn't what you expect

似乎如果你想使用get_object_vars,你必须从有权访问所有属性的上下文中使用它,即从你正在暴露的类中来看:

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

因此,想象一下我们将以上内容添加到RandomClass定义中:

echo json_encode( $a->getAllProperties() );

/// you will get {"var":123,"obj":{"time":1349777323}}

这是有效的,因为类的成员可以访问公共或私有的所有类的属性....正如我所说,以这种方式工作远远优越;优越,但并非总是可能。