Code on p.128
The code on p.128 is not going to work unless:
1) you rename the hasMore method of the collection iterator class to valid
2) you need to define some classes for Foo, Bar and FooBar
3) And, if you do all this and run the code, you'll still see nothing because this is not apparently an example that was meant to be run but rather read.
Here's a better example to use if you wish to stick to the tiresome and overused Foo,Bar, etc. vein, so that you can see something in your browser:
<?php
error_reporting(E_ALL);
require_once("class.collectioniterator.php");
require_once("class.Collection.php");
class Foo {
private $_name;
public function __construct() {
$this->_name = "Fooey";
}
public function __toString(){
return $this->_name;
}
}
class Bar {
private $_name;
public function __construct() {
$this->_name = "Barred";
}
public function __toString(){
return $this->_name;
}
}
class FooBar {
private $_name;
public function __construct() {
$this->_name = "FooBared";
}
public function __toString(){
return $this->_name;
}
}
/* add some items to the collection */
$objCol = new Collection();
$objCol->addItem(new Foo(), "foo1"); // key = "foo1"
$objCol->addItem(new Bar(), "bar1"); // key = "bar1"
$objCol->addItem(new FooBar()); // key = 0
$objCol->addItem(new FooBar()); // key = 1
/* Instantiate a CollectionIterator */
$objIt = new CollectionIterator($objCol);
/* $objIt->_keys now looks like this:
* $objIt->_keys[0] = "foo1";
* $objIt->_keys[1] = "bar1";
* $objIt->_keys[2] = 0;
* $objIt->_keys[3] = 1;
*/
echo '<h1>TEST of Collection Iterator methods</h1>';
$objIt->rewind(); // $_currIndex = 0;
$objFoo = $objIt->current(); // $_currIndex = 0, current key = "foo1"
// $objFoo = the first Foo object
echo '<p>Current Key is <b>',$objIt->key(), '</b><BR>';
echo 'Name of $objFoo is <b>', $objFoo->__toString(), '</b></p>';
$objIt->next(); // $_currIndex = 1;
$objBar = $objIt->current(); // $_currIndex = 1; current key = "bar1"
// $objBar = the Bar object
echo '<p>','Current Key is <b>',$objIt->key(),'</b><BR>';
echo 'Name of $objBar is <b>', $objBar->__toString(),'</b></p>';
$objIt->next(); // $_currIndex = 2;
$objFooBar = $objIt->current(); // $_currIndex = 2, current key = 0
// so $objFooBar is the first FooBar object
echo '<p>','Current Key is <b>', $objIt->key(),'</b><BR>';
echo 'Name of $objFooBar is <b>', $objFooBar->__toString(),'</b></p>';
$objIt->next(); // $_currIndex = 3;
$objFooBar2 = $objIt->current(); // $_currIndex = 3, current key = 1
// so $objFooBar is the 2nd FooBar object
echo '<p>Current Key is <b>', $objIt->key(),'</b><BR>';
echo 'Name of $objFooBar2 is <b>', $objFooBar->__toString(),'</b></p>';
?>
|