RE: [PHP-DEV] enhance fget to accept a callback
| From: | Rowan Collins | Date: | Mon, 24 Nov 2014 19:14:34 +0000 |
| Subject: | RE: [PHP-DEV] enhance fget to accept a callback | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-79131@lists.php.net to get a copy of this message | ||
On 23 November 2014 23:36:30 GMT, Bill Salak <bill@devtemple.com> wrote:
>The callback would be given the string as returned by fgets today. The
>functional equivalent to fgetjson today is handled by something like
>$handle = fopen(~some file~, 'r');
>while (($data = fgets($handle)) !== FALSE) {
> $data = json_decode($data, true);
> ...other stuff...
>}
>and would change to
>$handle = fopen(~some file~, 'r');
>$decode = json_decode($data, true);
>while (($data = fgets($handle,0,$decode)) !== FALSE) {
> ...other stuff...
>}
Since you need a function reference for the callback, you'd actually need a closure to capture
the options:
$decode = function($data) { return json_decode($data, true); };
This is actually more effort and code than the existing version, so I'm not sure what is
gained.
Either way, the likelihood is you'd want to wrap this into a user function. As I mentioned
earlier, making it into an Iterator is often useful, and potentially as simple as a generator
function a bit like this:
function fjsoniterator($fh) {
if ( ! feof($fh) ) {
yield json_decode(fgets($fh), true);
}
}
$fh = fopen(...);
foreach ( fjsoniterator($fh) as $data ) { ... }
Regards,
--
Rowan Collins
[IMSoP]