开发者

extend SplFileObject with fread method

PHP5 introduced an object-oriented file wrapper, SplFileObject. I guess I just found out 开发者_如何学Cwhy hardly anybody is using it. It's purely line-oriented, there is no fread() method - which the corresponding frwite seemed to suggest.

So now I'm wondering if I can extend it. I'm however not sure what's the better workaround. SplFileObject is not particular helpful in tucking the file pointer ($fp) away - it's either a private attribute or ZE-internal resource. So how would I extend it to get a fread method?

  • Implement fread() as string collecting loop with fgets(), with eventual seeking if only a specific size was requested and fgets read too far until the next \n line break.
  • Use a custom constructor, which opens the file a second time and stores a secondary file pointer, in case I want to call fread() instead of the parent class methods.

I'd go for the fgets workaround loop, but it sounds cumbersome and slow and provides for more potential pitfalls. OTOH opening a secondary file pointer seems not a good approach either and needs a custom destructor too.


You can call extend it and add an fread method that calls the fgetc method repeatedly, the desired number of times.

That said, I agree this is a weird limitation. Submit a feature request. If I'm not missing something, and fread method ought to be implemented.


Feature added in PHP5.6

. Added feature #65545 (SplFileObject::fread()) (Tjerk)

From https://github.com/php/php-src/blob/php-5.6.0RC2/NEWS

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜