The CallbackFilterIterator class

(PHP 5 >= 5.4.0)

Wstęp

Krótki opis klasy

CallbackFilterIterator extends FilterIterator implements Iterator , Traversable , OuterIterator {
/* Metody */
public __construct ( Iterator $iterator , callable $callback )
public string accept ( void )
/* Metody dziedziczone */
abstract bool FilterIterator::accept ( void )
mixed FilterIterator::current ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
bool FilterIterator::valid ( void )
}

Przykłady

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Przykład #1 Available callback arguments

<?php

/**
 * Callback for CallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current$key$iterator) {
    
// Your filtering code here
}

?>

Any callable may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Przykład #2 Callback basic examples

<?php

$dir 
= new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
function is_large_file($current) {
    return 
$current->isFile() && $current->getSize() > 104857600;
}
$large_files = new CallbackFilterIterator($dir'is_large_file');

// Filter directories
$files = new CallbackFilterIterator($dir, function ($current$key$iterator) {
    return 
$current->isDir() && ! $iterator->isDot();
});

?>

Spis treści

add a note add a note

User Contributed Notes 1 note

up
3
dave1010 at gmail dot com
1 year ago
Implementation for PHP < 5.4:

<?php
if (!class_exists('CallbackFilterIterator')) {   
    class
CallbackFilterIterator extends FilterIterator {
        protected
$callback;

       
// "Closure" type hint should be "callable" in PHP 5.4
       
public function __construct(Iterator $iterator, Closure $callback = null) {
           
$this->callback = $callback;
           
parent::__construct($iterator);
        }

        public function
accept() {
            return
call_user_func(
               
$this->callback,
               
$this->current(),
               
$this->key(),
               
$this->getInnerIterator()
            );
        }
    }
}

?>
To Top