In the section that you just read, I built a basic iterator class whose main task was to traverse the contents of a specified text file. Having discussed briefly the inner workings of this class, it'd be really useful to set up an example that shows it in action. Below I coded a short script that demonstrates how to work with the mentioned iterator, assuming that the text file that will be traversed has been defined like this: (data.txt)
line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10 Since the definition of the above "data.txt" file doesn't bear any further discussion, please look at the following code fragment. It shows a simple usage of the earlier "FileIterator" class, provided that the definition of the corresponding parent has been previously included in the script: // use FileIterator class try { // create instance of FileIterator $fit = new FileIterator(); // reset iterator pointer $fit->rewind(); // display current file line echo $fit->current(); // move iterator pointer forward $fit->next(); // display current file line echo $fit->current(); // move iterator pointer forward $fit->next(); // display current file line echo $fit->current(); // reset iterator pointer $fit->rewind(); // display current file line echo $fit->current(); }
// catch exceptions catch (Exception $e) { echo $e->getMessage(); exit(); } There you have it. Thanks to the implementation of a simple protected constructor within the base "DataIterator" class, I managed to build a neat hierarchy of classes that let you easily navigate the contents of a target text file. Although it's fair to admit that this particular example can be improved for the reasons given previously, it's handy for demonstrating a simple use of a restrictive constructor in PHP 5. As usual, feel free to introduce your own modifications to all of the code samples shown before, which hopefully will spark your creativity for implementing protected and private constructors when developing your PHP applications. Final thoughts In this introductory part of the series, I showed you a trivial example where a protected constructor was used to prevent the direct instantiation of a parent, generic array iterator class. While this approach will produce the expected results, it's admittedly pretty pointless because a stronger level of restriction can be achieved by declaring the class in question abstract. Since PHP 5 offers great support for working with abstract classes, in the next tutorial I'm going to recreate the example that you saw before, but this time by simply using an abstract iterator class. Don't miss the upcoming article!
blog comments powered by Disqus |
|
|
|
|
|
|
|