extend SplFileObject with fread method

SRBuckey5266

New Member
PHP5 introduced an object-oriented file wrapper, SplFileObject. I guess I just found out why 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.
 
Back
Top