I’m certain every programmer who wanted to something a bit more fancy came across this problem. You want to cycle through 2 or more values, and then start from the beginning again, but all of this easy and fast. The standard implementation I have seen so far is to define a variable, then count it up until it has reached a also predefined maximum value, and reset it to the start value. Rinse repeat.
Often this is paired with an array and keys to find the correct content. Sometimes a function is used as a wrapper (using static variables more often than not) and similar rather ugly things.
Well, what does keep a state in itself very well? A class of course.
On Aidan Lister’s page I cam across a very interesting piece of code that cycles between strings. You instantiate the class with the values to cycle through given to the constructor. Now from here on out all you do is use the variable, holding the object directly like it would contain the value you need directly, say an integer or a string. Through the magic method __toString() it then dispenses the current value and advances the pointer, or wraps it around to the start.
Very simple yet powerful and also some food for thought, as this exact method might work well on other problems.
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
You must be logged in to post a comment.