|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2016-09-16 19:20 UTC] bukka@php.net
-Package: json
+Package: JSON related
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 12:00:02 2025 UTC |
Description: ------------ json_encode() function does not accept Generator objects. This is I think a interesting optimization in the source code in userland, as it wouldn't be necessary anymore to transform what is yielded by the generator into a temporary array. From the userland point of view, it could be done via JsonSerializable interface implementation. Test script: --------------- <?php // Example 1 : minimal POC $callback = function(){ yield ['a', 'b', 'c', 'd']; yield ['e', 'f', 'g', 'h']; yield ['i', 'j', 'k', 'l']; yield ['m', 'n', 'o', 'p']; }; echo json_encode($callback(), JSON_PRETTY_PRINT) . PHP_EOL; // Example 2 : real-life example class Item { public $label; public function __consctruct($label) { $this->label = $label; } } class Collection { private $items = []; public function add(Item $item) { $this->items[] = $item; } public function walkItemLabels() { foreach ($this->items as $item) { yield $item->label; } } } $collection = new Collection(); $collection->add(new Item('Lorem')); $collection->add(new Item('Ipsum')); $collection->add(new Item('Dolor')); $collection->add(new Item('Sit')); $collection->add(new Item('Amet')); echo json_encode($collection->walkItemLabels(), JSON_PRETTY_PRINT) . PHP_EOL; Expected result: ---------------- // Example 1 [['a', 'b', 'c', 'd'],['e', 'f', 'g', 'h'],['i', 'j', 'k', 'l'],['m', 'n', 'o', 'p']] // Example 2 ['Lorem','Ipsum','Dolor,'Sit','Amet'] Actual result: -------------- // Example 1 {} // Example 2 {}