note 93715 added to control-structures.foreach
| From: | mazdak dot farrokhzad at piratpartiet dot se | Date: | Thu, 24 Sep 2009 04:49:14 +0000 |
| Subject: | note 93715 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-161005@lists.php.net to get a copy of this message | ||
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);
?>
----
Server IP: 212.63.193.10
Probable Submitter: 81.235.227.65
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/93715
Del: integrated -- https://master.php.net/note/delete/93715/integrated
Del: useless -- https://master.php.net/note/delete/93715/useless
Del: bad code -- https://master.php.net/note/delete/93715/bad+code
Del: spam -- https://master.php.net/note/delete/93715/spam
Del: non-english -- https://master.php.net/note/delete/93715/non-english
Del: in docs -- https://master.php.net/note/delete/93715/in+docs
Del: other reasons-- https://master.php.net/note/delete/93715
Reject -- https://master.php.net/note/reject/93715
Search -- https://master.php.net/manage/user-notes.php