php的SPL(Standard PHP Library)简介

SPL(Standard PHP Library)简介

php5以后的版本引入了SPL(Standard PHP Library)。这个库定义了很多有用的接口和类以及少量函数(例如spl_autoload),功能非常强大。大家可以通过print_r(spl_classes());来打印出自己的php版本所支持的所有spl类和接口。
目前已经有不少项目(例如ZF)应用了spl,所以学习spl是很有必要的。

这里介绍几个常用的spl类和接口。

一、Countable

count是php最常用的函数之一,在早期的php版本,count只能用于计算数组的单元数目,对于其他类型包括对象count的返回值都是1(NULL除外,count(NULL)返回0),在php5以后,我们可以通过让对象实现Countable接口来定义count的调用。

Countable接口只有一个公用的成员方法count()。

举个例子:

<?php  
class A implements Countable  
{  
    private $var = array(1, 2, 3);  
      
    public function count()  
    {  
        return count($this->var);  
    }  
}  
$a = new A;  
echo count($a); 

<?php
class A implements Countable
{
    private $var = array(1, 2, 3);
   
    public function count()
    {
        return count($this->var);
    }
}
$a = new A;
echo count($a);
本例将输出 3 。

二、ArrayObject
ArrayObject是数组的封装类,它能够把数组转成对象存储。举个例子:

<?php  
$arr = array(  
    'a' => 1,  
    'b' => 'str',  
    'c' => array(1)  
);  
$obj = new ArrayObject($arr);  
var_dump($obj);  
$arr2 = $obj->getArrayCopy(); // 返回对象的公用成员变量数组  
print_r($arr2); 

<?php
$arr = array(
    'a' => 1,
    'b' => 'str',
    'c' => array(1)
);
$obj = new ArrayObject($arr);
var_dump($obj);
$arr2 = $obj->getArrayCopy(); // 返回对象的公用成员变量数组
print_r($arr2);
本例将输出:
object(ArrayObject)#1 (3) {
["a"]=>
int(1)
["b"]=>
string(3) “str”
["c"]=>
array(1) {
    [0]=>
    int(1)
}
}
Array
(
    [a] => 1
    [b] => str
    [c] => Array
        (
            [0] => 1
        )

)

三、IteratorAggregate
对象的原始迭代器接口是Iterator,不过这个接口定义的公用方法有好几个:
current()
key()
next()
rewind()
valid()
用起来稍微有点不方便,所以spl同时提供了一个简化版的或者说集成版的迭代器接口IteratorAggregate。
这个接口只有一个公用方法
Iterator getIterator()
这个方法需要返回的是对象的Iterator。
上面提到的ArrayObject类就是实现了IteratorAggregate接口的,举个例子:

<?php  
class A implements IteratorAggregate  
{  
    private $var = array(1, 2, 3);  
      
    public function getIterator()  
    {  
        return new ArrayObject($this->var);  
    }  
}  
$a = new A();  
foreach ($a as $b) {  
    echo "$b ";  

<?php
class A implements IteratorAggregate
{
    private $var = array(1, 2, 3);
   
    public function getIterator()
    {
        return new ArrayObject($this->var);
    }
}
$a = new A();
foreach ($a as $b) {
    echo "$b ";
}
本例将输出:
1
2
3

查看更多的类和接口可以访问

http://www.php.net/~helly/php/ext/spl/