note 93715 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:27:00 +0000 |
| Subject: | note 93715 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191960@lists.php.net to get a copy of this message | ||
Note Submitter: mazdak dot farrokhzad at piratpartiet dot se
----
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);
?>