code_junkie

PHP: __toString() and json_encode() not playing well together

Nov 13th, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. class A
  2. {
  3. protected $a;
  4.  
  5. public function __construct()
  6. {
  7. $this->a = array( new B, new B );
  8. }
  9.  
  10. public function __toString()
  11. {
  12. return json_encode( $this->a );
  13. }
  14. }
  15.  
  16. class B
  17. {
  18. protected $b = array( 'foo' => 'bar' );
  19.  
  20. public function __toString()
  21. {
  22. return json_encode( $this->b );
  23. }
  24. }
  25.  
  26. $a = new A();
  27.  
  28. echo $a;
  29.  
  30. [{},{}]
  31.  
  32. [{"foo":"bar"},{"foo":"bar"}]
  33.  
  34. class a
  35. {
  36. public function __set( $prop, $value )
  37. {
  38. echo __METHOD__, PHP_EOL;
  39. $this->$prop = $value;
  40. }
  41.  
  42. public function __toString()
  43. {
  44. return json_encode( $this );
  45. }
  46. }
  47.  
  48. $a = new a;
  49. $a->foo = 'bar';
  50. $a->foo = 'baz';
  51.  
  52. echo $a;
  53.  
  54. class a
  55. {
  56. public $foo;
  57.  
  58. public function setFoo( $value )
  59. {
  60. $this->foo = $value;
  61. }
  62.  
  63. public function __toString()
  64. {
  65. return json_encode( $this );
  66. }
  67. }
  68.  
  69. $a = new a;
  70. $a->setFoo( 'bar' );
  71.  
  72. echo $a;
  73.  
  74. <?php
  75.  
  76. class a implements IteratorAggregate
  77. {
  78. public $foo = 'bar';
  79. protected $bar = 'baz';
  80.  
  81. public function getIterator()
  82. {
  83. echo __METHOD__;
  84. }
  85. }
  86.  
  87. echo json_encode( new a );
  88.  
  89. [{"b":{"foo":"bar"}},{"b":{"foo":"bar"}}]
  90.  
  91. [{"foo":"bar"},{"foo":"bar"}]
  92.  
  93. class B
  94. {
  95. protected $b = array( 'foo' => 'bar' );
  96.  
  97. public function __get($name)
  98. {
  99. return json_encode( $this->$name );
  100. }
  101. }
  102.  
  103. class A
  104. {
  105. protected $a;
  106.  
  107. public function __construct()
  108. {
  109. $b1 = new B;
  110. $b2 = new B;
  111. $this->a = array( json_decode($b1->b), json_decode($b2->b) );
  112. }
  113.  
  114. public function __toString()
  115. {
  116. return json_encode( $this->a );
  117. }
  118. }
  119.  
  120. class A
  121. {
  122. protected $a;
  123.  
  124. public function __construct()
  125. {
  126. $this->a = array( (string)new B, (string)new B );
  127. }
  128.  
  129. public function __toString()
  130. {
  131. return json_encode( $this->a );
  132. }
  133. }
  134.  
  135. $this->a = array( json_decode((string)new B), json_decode((string)new B) );
  136.  
  137. $b1 = new B;
  138. $b2 = new B;
  139. $this->a = array( $b1->toArray(), $b2->toArray() );
Add Comment
Please, Sign In to add comment