インターフェイス

目次

SPL にはインターフェイスが用意されています。

定義済みのインターフェイスとクラス も参照ください。

インターフェイス一覧

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject

Countable インターフェイス

はじめに

Countable を実装したクラスは、 count 関数で使用することができます。

インターフェイス概要

Countable
/* メソッド */
public int Countable::count()

OuterIterator インターフェイス

はじめに

OuterIterator を実装したクラスは、 イテレータ群の反復処理に使うことができます。

インターフェイス概要

OuterIterator extends Iterator
/* メソッド */
public Iteratornull OuterIterator::getInnerIterator()
/* 継承したメソッド */
public mixed Iterator::current()
public mixed Iterator::key()
public void Iterator::next()
public void Iterator::rewind()
public bool Iterator::valid()

RecursiveIterator インターフェイス

はじめに

RecursiveIterator を実装したクラスは、 イテレータ群を再帰的に反復処理するときに使うことができます。

インターフェイス概要

RecursiveIterator extends Iterator
/* メソッド */
public RecursiveIteratornull RecursiveIterator::getChildren()
public bool RecursiveIterator::hasChildren()
/* 継承したメソッド */
public mixed Iterator::current()
public mixed Iterator::key()
public void Iterator::next()
public void Iterator::rewind()
public bool Iterator::valid()

SeekableIterator インターフェイス

はじめに

Seekable イテレータです。

インターフェイス概要

SeekableIterator extends Iterator
/* メソッド */
public void SeekableIterator::seek(int $offset)
/* 継承したメソッド */
public mixed Iterator::current()
public mixed Iterator::key()
public void Iterator::next()
public void Iterator::rewind()
public bool Iterator::valid()

例1 基本的な使用法

この例では、SeekableIterator を作成して位置を移動し、無効な位置を扱います。

<?php
class MySeekableIterator implements SeekableIterator {

    private 
$position;

    private 
$array = array(
        
"first element",
        
"second element",
        
"third element",
        
"fourth element"
    
);

    
/* SeekableIterator インターフェイスで必要なメソッド群 */

    
public function seek($position) {
      if (!isset(
$this->array[$position])) {
          throw new 
OutOfBoundsException("invalid seek position ($position)");
      }

      
$this->position $position;
    }

    
/* Iterator インターフェイスで必要なメソッド群 */
    
    
public function rewind() {
        
$this->position 0;
    }

    public function 
current() {
        return 
$this->array[$this->position];
    }

    public function 
key() {
        return 
$this->position;
    }

    public function 
next() {
        ++
$this->position;
    }

    public function 
valid() {
        return isset(
$this->array[$this->position]);
    }
}

try {

    
$it = new MySeekableIterator;
    echo 
$it->current(), "\n";
    
    
$it->seek(2);
    echo 
$it->current(), "\n";
    
    
$it->seek(1);
    echo 
$it->current(), "\n";
    
    
$it->seek(10);
    
} catch (
OutOfBoundsException $e) {
    echo 
$e->getMessage();
}
?>

上の例の出力は、 たとえば以下のようになります。

first element
third element
second element
invalid seek position (10)