note 94905 deleted from control-structures.foreach by thiago

From: Date: Wed, 02 Dec 2009 14:31:55 +0000
Subject: note 94905 deleted from control-structures.foreach by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-163490@lists.php.net to get a copy of this message
Note Submitter: ganesh dot bagde at gmail dot com ---- This is a really silly example of how you can implement foreach for objects in a really crazy way... It's not something you should use... <?php /** * Same as foreach, for objects... * * @param object|array $_collection * @param callback $_lambda * @param mixed $_data optional * @return void */ function loop($_collection, $_lambda, $_data = null) { if(is_array($_collection)) { foreach($_collection as $key => $value) { if(is_null($_data)) $_lambda($key, $value); else $_lambda($key, $value, $_data); } } elseif(is_object($_collection)) { $iter = $_collection->getIterator(); $iter->rewind(); while($iter->valid()) { if(is_null($_data)) $_lambda($iter->key(), $iter->current()); else $_lambda($iter->key(), $iter->current(), $_data); $iter->next(); } } else trigger_error('Only Accepts Objects or Arrays', E_USER_ERROR); } // and this is how to use it... $data = "some random data"; // you can place $this here loop(new ArrayObject(array(1,2,3,4)), function(&$_key, &$_value, &$_data) { echo $_key.$_value.$_data; }, $data); ?>

« previous php.notes (#163490) next »