oo and iterator - excercise???

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
renathy
Forum Newbie
Posts: 1
Joined: Tue Mar 31, 2009 6:59 am

oo and iterator - excercise???

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: oo and iterator - excercise???

Post 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.
Post Reply