來點技術性文章
證明我腦子還是行的吧

PHP 有一些 interface ,在寫 class 時非常好用,只是在 php.net 裡面很難找到哪裡有寫
我來列舉一下

interface Iterator {
    public function rewind( );
    public function current( );
    public function key( );
    public function next( );
    public function valid( );
}

implements Iterator 的 class 可以被直接拿來 foreach ( $obj as $key => $value ) { ... } 使用
相當於
for ( $obj->rewind( ); $obj->valid( ); $obj->next( ) ) {
  $key = $obj->key( );
  $value = $obj->current( );
}

===========================
interface IteratorAggregate {
  public function getIterator( );
}
implements IteratorAggregate 的 class 也可以直接拿來 foreach ($obj as $key => $value) { ... } 使用
相當於
foreach ($obj->getIterator( ) as $key => $value ) { ... }

===========================
interface Countable {
    public function count( );
}

implements Countable 的 class 可以直接拿來 count( $obj ); ,相當於 $obj->count( );
===========================
interface SeekableIterator {
   public function rewind( );
    public function current( );
    public function key( );
    public function next( );
    public function valid( );
    public function seek( $pos );
}

implements SeekableIterator 的 class 除了可以被直接拿來 foreach ( $obj as $key => $value ) { ... } 使用 以外,還可以用  $obj->seek($pos) 去取得他的值
(不能用 $obj[$pos] 去取喔,要用 $obj[$pos] 必需要 implements ArrayAccess)
===========================
interface ArrayAccess {
    offsetExists ($offset)
    offsetGet ($offset)
    offsetSet ($offset, $value)
    offsetUnset ($offset)
}

implements ArrayAccess 的 class 可以被當作 Array 使用
Ex: isset( $obj[$i] )   ==> $obj->offsetExists($i);
      $a = $obj[$i] ====>  $a = $obj->offsetGet($i);
      $obj[$i] = $value;  ===> $obj->offsetSet($i, $value);
      $obj[ ] = $value ===> $obj->offsetSet(NULL, $value);
      unset($obj[$i]) ==> $obj->offsetUnset($i);

如果想要 count($obj) 就要再 implements Countable
==========================
interface Serializable {
    public function serialize( );
    public function unserialize( $serialized )
}

implements Serializable 的 class 你可以去 serialize 他
$word = serialize( $obj );   ==> $word = $obj->serialize( );
另外,他會自動把你的 ->serialize( ) 傳出來的 serialize 文字外面再包一層
C:X:"你的Class Name":XX: { 你的 Serialize 內容 }
所以你直接 unserialize( 這個字串 ); 他就會知道要去呼叫哪一個 class 的 unserialize
arrow
arrow
    全站熱搜

    榮尼王 發表在 痞客邦 留言(1) 人氣()