note 106231 modified in class.arrayiterator by danbrown
| From: | danbrown@php.net | Date: | Thu, 20 Oct 2011 17:06:21 +0000 |
| Subject: | note 106231 modified in class.arrayiterator by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184023@lists.php.net to get a copy of this message | ||
Need a callback on an iterated value, but don't have PHP 5.4+? This makes is stupid easy:
<?php
class ArrayCallbackIterator extends ArrayIterator {
private $callback;
public function __construct($value, $callback) {
parent::__construct($value);
$this->callback = $callback;
}
public function current() {
$value = parent::current();
return call_user_func($this->callback, $value);
}
}
?>
You can use it pretty much exactly as the Array Iterator:
<?php
$iterator1 = new ArrayCallbackIterator($valueList, "callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object,
"callback_class_method"));
?>
--was--
Need a callback on an iterated value, but don't have PHP 5.4+? This makes is stupid easy:
class ArrayCallbackIterator extends ArrayIterator {
private $callback;
public function __construct($value, $callback) {
parent::__construct($value);
$this->callback = $callback;
}
public function current() {
$value = parent::current();
return call_user_func($this->callback, $value);
}
}
You can use it pretty much exactly as the Array Iterator:
$iterator1 = new ArrayCallbackIterator($valueList, "callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object,
"callback_class_method"));
http://php.net/manual/en/class.arrayiterator.php