php 미리 정 의 된 인터페이스

7482 단어 PHP

Traversable
Traversable {

}

 
역할:foreach 로 옮 겨 다 니 는 인 터 페 이 스 를 사용 할 수 있 는 지 확인 합 니 다.
php 코드 에 서 는 사용 할 수 없습니다.내부 의 PHP 클래스(C 로 쓰 는 클래스)만 Traversable 인터페이스 phop 코드 에서 Iterator 나 Iterator Aggregate 인 터 페 이 스 를 사용 하여 옮 겨 다 닐 수 있 습 니 다.
이 인 터 페 이 스 는 아무런 방법 이 없다.그 역할 은 모든 종류의 기본 인터페이스 일 뿐이다.
#             foreach    ,  Iterator     
class man{
    
}

$p = new man();
var_dump($p instanceof  man); #false

 
if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here

 
Iterator 가 이 인 터 페 이 스 를 실현 하 는 대상 은 자신의 내부 데 이 터 를 교체 할 수 있 습 니 다.
Iterator extends Traversable  
{  
    //               
    abstract public mixed current(void)  
    //                  
    abstract public scalar key(void)  
    //                
    abstract public void next(void)  
    //                
    abstract public void rewind(void)  
    //                  ,      rewind()  next()    
    abstract public boolean valid(void)  
} 

 
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
            "firstelement",
            "secondelement",
            "lastelement",
    );

    public function __construct() {
        $this->position = 0;
    }

    function rewind() {
//         var_dump(__METHOD__);
        $this->position = 0;
    }

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

    function key() {
//         var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
//         var_dump(__METHOD__);
        ++$this->position;
    }

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

$it = new myIterator;

foreach($it as $key => $value) {
    echo "{$key}|{$value}";
    echo "
"; } /** 0|firstelement 1|secondelement 2|lastelement */

 
 
 
 
 
http://www.nowamagic.net/librarys/veda/detail/2167
http://www.php.net/manual/zh/reserved.interfaces.php

좋은 웹페이지 즐겨찾기