In the preceding segment, you just saw that the definition of the file iterator class derived from the base array iterator remained exactly the same, which means that in this particular case, putting it to work wouldn’t be radically different from other code samples shown previously. But is this really true? Well, I have to say yes, and the following code fragment demonstrates that: // use FileIterator class try { // create instance of FileIterator $fit = new FileIterator('sample_file.txt'); // 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(); } Nothing really unexpected, right? As you can see, iterating over the contents of a text file is a process that doesn’t differ at all from the example that you saw in the introductory installment. In addition, it’s valid to stress that even though turning the base iterator into an abstract class permitted us to get rid of a protected constructor, there are other scenarios where a restrictive constructor can be of great help to implement certain patterns, or even assure that a class will be used out of the object's context. However, some of these topics will be discussed in more detail in upcoming parts of the series. Final thoughts In this second episode of the series, I rebuilt the example application developed in the previous tutorial, which used a protected constructor to prevent the instantiation of the base array iterator class. In this case, it’s valid to stress that a better result was achieved by declaring the iterator in question abstract, but hopefully the example was useful enough to demonstrate a simple utilization of a restrictive constructor in a concrete situation. As I said in the introduction of this series, protected and private constructors can be used in a great diversity of scenarios and contexts. Therefore, in the subsequent tutorial I’m going to explain how to work with a private constructor to implement a Singleton database access class. Don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|