Page 1 of 1

oo and iterator - excercise???

Posted: Wed Oct 06, 2010 8:48 am
by renathy
I have an execercise to do, but I cannot figure out the main idea of it...

I am given the following code:

Code: Select all

<?php
$test = new testClass();
$test->a = 'a';
$test->b = 'b';
foreach( $test as $key => $value ){
echo $key . ' : ' . $value . "\n";
}
?>
1) I need to use PHP5OO and Iterator Design pattern
2) I need to finish the above code, so it displays
a : a
b : b

3) If new elements are added to testClass, they should be displayed as well.


I undesrtand the idea of Iterator, i can write it for my own custom classe (for example, to iterate via collection in my class or database data). However, I cannot understand the idea of this particular excercise - what custom things should be implemented in my iterator? How my custom Iterator should iterate?

Actually, I can simply create class testClass with two public variables "public a" and "public b" and that's it, why I need iterator??? Foreach loop already iterates through all public variables by default...????

Could you please help me to figure out the idea of the excercise???

Renate

Re: oo and iterator - excercise???

Posted: Wed Oct 06, 2010 9:58 am
by requinix
The idea of the exercise is to teach you new stuff. Heaven forbid that what little you know now turns out to be less than adequate sometime in the future.

testClass needs to implement Traversable somehow. I suggest IteratorAggregate. Why? Because this is the easiest way of providing Traversable after using the easiest method for:
testClass also needs to support adding variables. Actual member variables are not the point. In fact, I bet you'll lose points if you try to do it that way. Look at the magic methods __get and __set.