note 54222 added to ref.spl

From: Date: Mon, 27 Jun 2005 19:11:04 +0000
Subject: note 54222 added to ref.spl
Groups: php.notes 
Request: Send a blank email to php-notes+get-91035@lists.php.net to get a copy of this message
Just a follow up on dave at tunasoft's post. To give his example of ArrayAccess use of foreach, it's easiest to implement IteratorAggregate and use the ArrayIterator object as the iterator, as below: <?php class Collection implements ArrayAccess,IteratorAggregate { public $objectArray = Array(); //**these are the required iterator functions function offsetExists($offset) { if(isset($this->objectArray[$offset])) return TRUE; else return FALSE; } function & offsetGet($offset) { if ($this->offsetExists($offset)) return $this->objectArray[$offset]; else return (false); } function offsetSet($offset, $value) { if ($offset) $this->objectArray[$offset] = $value; else $this->objectArray[] = $value; } function offsetUnset($offset) { unset ($this->objectArray[$offset]); } function & getIterator() { return new ArrayIterator($this->objectArray); } //**end required iterator functions public function doSomething() { echo "I'm doing something"; } } ?> I LOVE the new SPL stuff in PHP. The above allows you to have methods inside of your array, and when treated as an array the data components are returned, such as: <?php class Contact { protected $name = NULL; public function set_name($name) { $this->name = $name; } public function get_name() { return ($this->name); } } $bob = new Collection(); $bob->doSomething(); $bob[] = new Contact(); $bob[5] = new Contact(); $bob[0]->set_name("Superman"); $bob[5]->set_name("a name of a guy"); foreach ($bob as $aContact) { echo $aContact->get_name() . "\r\n"; } ?> Would work just fine. This make code so much simpler and easy to follow, it's great. This is exactly the direction I had hoped PHP5 was going! ---- Manual Page -- http://www.php.net/manual/en/ref.spl.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+54222 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54222&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+54222&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#91035) next »