PHP SPL(PHP 標準庫)

1、什麼是spl庫?

SPL是用於解決典型問題(standard problems)的一組接口與類的集合。php

此擴展只能在php 5.0之後使用,從PHP 5.3.0 再也不被關閉,會一直有效.成爲php內核組件一部份。node

SPL提供了一組標準數據結構。python

 

2、SPL如何使用?

1.構建此擴展不須要其餘擴展。數組

更詳細的狀況可參考 http://php.net/manual/zh/spl.datastructures.php數據結構

雙向鏈表

雙鏈表是一種重要的線性存儲結構,對於雙鏈表中的每一個節點,不單單存儲本身的信息,還要保存前驅和後繼節點的地址。this

SplDoublyLinkedListspa

SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
    /* 方法 */
    public __construct ( void )
    public void add ( mixed $index , mixed $newval )
    public mixed bottom ( void )//雙鏈表的尾部節點
    public int count ( void )//雙聯表元素的個數
    public mixed current ( void )//當前記錄
    public int getIteratorMode ( void ) //獲取迭代模式
    public bool isEmpty ( void )//檢測雙鏈表是否爲空
    public mixed key ( void )//當前節點索引
    public void next ( void )//移到下條記錄
    public bool offsetExists ( mixed $index )//指定index處節點是否存在
    public mixed offsetGet ( mixed $index )//獲取指定index處節點值
    public void offsetSet ( mixed $index , mixed $newval )//設置指定index處值
    public void offsetUnset ( mixed $index )//刪除指定index處節點
    public mixed pop ( void )//從雙鏈表的尾部彈出元素
    public void prev ( void )//移到上條記錄
    public void push ( mixed $value )//添加元素到雙鏈表的尾部
    public void rewind ( void )//將指針指向迭代開始處
    public string serialize ( void )//序列化存儲
    public void setIteratorMode ( int $mode )//設置迭代模式
    public mixed shift ( void )//雙鏈表的頭部移除元素
    public mixed top ( void )//雙鏈表的頭部節點
    public void unserialize ( string $serialized )//反序列化
    public void unshift ( mixed $value )//雙鏈表的頭部添加元素
    public bool valid ( void )//檢查雙鏈表是否還有節點
}

 接下來是使用方法:.net

$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->push('d');

$list->unshift('top');
$list->shift();

$list->rewind();//rewind操做用於把節點指針指向Bottom所在的節點
echo 'curren node:'.$list->current()."<br />";//獲取當前節點

$list->next();//指針指向下一個節點
echo 'next node:'.$list->current()."<br />";

$list->next();
$list->next();
$list->prev();//指針指向上一個節點
echo 'next node:'.$list->current()."<br />";

if($list->current())
    echo 'current node is valid<br />';
else
    echo 'current node is invalid<br />';


if($list->valid())//若是當前節點是有效節點,valid返回true
    echo "valid list<br />";
else
    echo "invalid list <br />";


var_dump(array(
    'pop' => $list->pop(),
    'count' => $list->count(),
    'isEmpty' => $list->isEmpty(),
    'bottom' => $list->bottom(),
    'top' => $list->top()
));

$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
var_dump($list->getIteratorMode());

for($list->rewind(); $list->valid(); $list->next()) {
    echo $list->current().PHP_EOL;
}

var_dump($a = $list->serialize());
//print_r($list->unserialize($a));

$list->offsetSet(0,'new one');
$list->offsetUnset(0);
var_dump(array(
    'offsetExists' => $list->offsetExists(4),
    'offsetGet' => $list->offsetGet(0),

));
var_dump($list);

//堆棧,先進後出
$stack = new SplStack();//繼承自SplDoublyLinkedList類

$stack->push("a<br />");
$stack->push("b<br />");

echo $stack->pop();
echo $stack->pop();
echo $stack->offsetSet(0,'B');//堆棧的offset=0是Top所在的位置,offset=1是Top位置節點靠近bottom位置的相鄰節點,以此類推
$stack->rewind();//雙向鏈表的rewind和堆棧的rewind相反,堆棧的rewind使得當前指針指向Top所在的位置,而雙向鏈表調用以後指向bottom所在位置
echo 'current:'.$stack->current().'<br />';

$stack->next();//堆棧的next操做使指針指向靠近bottom位置的下一個節點,而雙向鏈表是靠近top的下一個節點
echo 'current:'.$stack->current().'<br />';
echo '<br /><br />';

//隊列,先進先出
$queue = new SplQueue();//繼承自SplDoublyLinkedList類

$queue->enqueue("a<br />");//插入一個節點到隊列裏面的Top位置
$queue->enqueue("b<br />");

$queue->offsetSet(0,'A');//堆棧的offset=0是Top所在的位置,offset=1是Top位置節點靠近bottom位置的相鄰節點,以此類推

echo $queue->dequeue();
echo $queue->dequeue();

echo "<br /><br />";

堆(Heap)就是爲了實現優先隊列而設計的一種數據結構,它是經過構造二叉堆(二叉樹的一種)實現。根節點最大的堆叫作最大堆或大根堆(SplMaxHeap),根節點最小的堆叫作最小堆或小根堆(SplMinHeap)。二叉堆還經常使用於排序(堆排序)設計

abstract SplHeap implements Iterator , Countable {
    /* 方法 用法同雙向鏈表一致 */
    public __construct ( void )
    abstract protected int compare ( mixed $value1 , mixed $value2 )
    public int count ( void )
    public mixed current ( void )
    public mixed extract ( void )
    public void insert ( mixed $value )
    public bool isEmpty ( void )
    public mixed key ( void )
    public void next ( void )
    public void recoverFromCorruption ( void )
    public void rewind ( void )
    public mixed top ( void )
    public bool valid ( void )
}

使用方法:指針

//堆
class MySplHeap extends SplHeap{
    //compare()方法用來比較兩個元素的大小,絕對他們在堆中的位置
    public function compare( $value1, $value2 ) {
        return ( $value1 - $value2 );
    }
}

$obj = new MySplHeap();

$obj->insert(0);
$obj->insert(1);
$obj->insert(2);
$obj->insert(3);
$obj->insert(4);

echo $obj->top();//4
echo $obj->count();//5

foreach ($obj as $item) {
    echo $item."<br />";
}

陣列

優先隊列也是很是實用的一種數據結構,能夠經過加權對值進行排序,因爲排序在php內部實現,業務代碼中將精簡很多並且更高效。經過SplPriorityQueue::setExtractFlags(int  $flag)設置提取方式能夠提取數據(等同最大堆)、優先級、和二者都提取的方式。

SplFixedArray implements Iterator , ArrayAccess , Countable {
  /* 方法 */
  public __construct ([ int $size = 0 ] )
  public int count ( void )
  public mixed current ( void )
  public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] )
  public int getSize ( void )
  public int key ( void )
  public void next ( void )
  public bool offsetExists ( int $index )
  public mixed offsetGet ( int $index )
  public void offsetSet ( int $index , mixed $newval )
  public void offsetUnset ( int $index )
  public void rewind ( void )
  public int setSize ( int $size )
  public array toArray ( void )
  public bool valid ( void )
  public void __wakeup ( void )
}

使用方法:

$arr = new SplFixedArray(4);
$arr[0] = 'php';
$arr[1] = 1;
$arr[3] = 'python';

//遍歷, $arr[2] 爲null
foreach($arr as $v) {
    echo $v . PHP_EOL;
}

//獲取數組長度
echo $arr->getSize(); //4

//增長數組長度
$arr->setSize(5);
$arr[4] = 'new one';

//捕獲異常
try{
    echo $arr[10];
} catch (RuntimeException $e) {
    echo $e->getMessage();
}

映射

用來存儲一組對象的,特別是當你須要惟一標識對象的時候。

SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess {
  /* 方法 */
  public void addAll ( SplObjectStorage $storage )
  public void attach ( object $object [, mixed $data = NULL ] )
  public bool contains ( object $object )
  public int count ( void )
  public object current ( void )
  public void detach ( object $object )
  public string getHash ( object $object )
  public mixed getInfo ( void )
  public int key ( void )
  public void next ( void )
  public bool offsetExists ( object $object )
  public mixed offsetGet ( object $object )
  public void offsetSet ( object $object [, mixed $data = NULL ] )
  public void offsetUnset ( object $object )
  public void removeAll ( SplObjectStorage $storage )
  public void removeAllExcept ( SplObjectStorage $storage )
  public void rewind ( void )
  public string serialize ( void )
  public void setInfo ( mixed $data )
  public void unserialize ( string $serialized )
  public bool valid ( void )
}

使用方法:

class A {
    public $i;
    public function __construct($i) {
        $this->i = $i;
    }
}
 
$a1 = new A(1);
$a2 = new A(2);
$a3 = new A(3);
$a4 = new A(4);
 
$container = new SplObjectStorage();
 
//SplObjectStorage::attach 添加對象到Storage中
$container->attach($a1);
$container->attach($a2);
$container->attach($a3);
 
//SplObjectStorage::detach 將對象從Storage中移除
$container->detach($a2);
 
//SplObjectStorage::contains用於檢查對象是否存在Storage中
var_dump($container->contains($a1)); //true
var_dump($container->contains($a4)); //false
 
//遍歷
$container->rewind();
while($container->valid()) {
    var_dump($container->current());
    $container->next();
}

固定長度數組

顧名思義,固定長度的數組

SplFixedArray implements Iterator , ArrayAccess , Countable {
    /* 方法 */
    public __construct ([ int $size = 0 ] )
    public count ( void ) : int
    public current ( void ) : mixed
    public static fromArray ( array $array [, bool $save_indexes = TRUE ] ) : SplFixedArray
    public getSize ( void ) : int
    public key ( void ) : int
    public next ( void ) : void
    public offsetExists ( int $index ) : bool
    public offsetGet ( int $index ) : mixed
    public offsetSet ( int $index , mixed $newval ) : void
    public offsetUnset ( int $index ) : void
    public rewind ( void ) : void
    public setSize ( int $size ) : bool
    public toArray ( void ) : array
    public valid ( void ) : bool
    public __wakeup ( void ) : void
}

使用方法:

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
    var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[-1]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[5]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}
?>
相關文章
相關標籤/搜索