Published on : 02.05.2010 Category : General php tips Viewed : 40 times.
Allows you to easily keep track of a series of items as either odd or even. Each time you check (using the "which" method) the counter increments so that the next time you check the state will have changed. This is the perfect class for using when you're outputting an HTML table and want to use different classes to differentiate between odd and even rows. Simply create a new instance and call OddEven->which() for each row!
Code:
/** * Allows you to easily keep track of rows of items as either odd or even. * Each time you check (using the "which" method) the counter increments so that * the next time you check the state will have changed. * * Jonathan Spalink * Dec. 2009 */ class OddEven { private $counter; private $odd; private $even;
const ODD = "odd"; const EVEN = "even"; /** * Constructor method to create a new OddEven counter * * @param String $odd The value to return when the counter is Odd * @param String $even The value to return when the counter is Even */ public function __construct($odd=self::ODD, $even=self::EVEN) { $this->counter = 1; $this->odd = $odd; $this->even = $even; }
/** * Increase the counter by 1 and return the old value * * @return Int The value of the counter before it is incremented */ public function increment() { return $this->counter++; }
/** * Resets the counter * * @param Int $initial The value at which to start the counter */ public function reset($initial=1) { $this->counter = $initial; }
/** * Runs an interation of the counter and returns whether its Odd or Even. * This also increments the counter by 1. * * @return String Odd or Even? */ public function which() { $now = $this->increment(); return ($now % 2 ? $this->odd : $this->even); }
/** * Static invocation of the OddEven class to simply check a number without * futher complications. If you don't pass in $odd or $even then the class * defaults are used. * * @param int $number The number to check * @param mixed $odd Value to return if number is odd * @param mixed $even Value to return if number is even * @return mixed $odd or $even */ static public function OddOrEven($number, $odd=self::ODD, $even=self::EVEN) { return ($number % 2 ? $odd : $even); }