我把SPL分为四个部分:Iterator,Classes,Datastructures,Function;而其中classes是就是做一些类的介绍(Iterator与Datastructures相关的类在各自文章内),在介绍这些类之前,先介绍几个接口:

ArrayAccess(数组式访问)接口

http://php.net/manual/zh/class.arrayaccess.php#class.arrayaccess

只要实现了这个接口,就可以使得object像array那样操作。ArrayAccess界面包含四个必须部署的方法,这四个方法分别传入的是array的key和value,:

* offsetExists($offset)
This method is used to tell php if there is a value for the key specified by offset. It should return true or false.检查一个偏移位置是否存在* offsetGet($offset)
This method is used to return the value specified by the key offset.获取一个偏移位置的值* offsetSet($offset, $value)
This method is used to set a value within the object, you can throw an exception from this function for a read-only collection. 获取一个偏移位置的值* offsetUnset($offset)
This method is used when a value is removed from an array either through unset() or assigning the key a value of null. In the case of numerical arrays, this offset should not be deleted and the array should not be reindexed unless that is specifically the behavior you want. 复位一个偏移位置的值

/*** A class that can be used like an array*/
class Article implements ArrayAccess{public $title;public $author;public $category;function __construct($title , $author , $category){$this->title = $title;$this->author = $author;$this->category = $category;}/*** Defined by ArrayAccess interface* Set a value given it's key e.g. $A['title'] = 'foo';* @param mixed key (string or integer)* @param mixed value* @return void*/function offsetSet($key , $value){if (array_key_exists($key , get_object_vars($this))) {$this->{$key} = $value;}}/*** Defined by ArrayAccess interface* Return a value given it's key e.g. echo $A['title'];* @param mixed key (string or integer)* @return mixed value*/function offsetGet($key){if (array_key_exists($key , get_object_vars($this))) {return $this->{$key};}}/*** Defined by ArrayAccess interface* Unset a value by it's key e.g. unset($A['title']);* @param mixed key (string or integer)* @return void*/function offsetUnset($key){if (array_key_exists($key , get_object_vars($this))) {unset($this->{$key});}}/*** Defined by ArrayAccess interface* Check value exists, given it's key e.g. isset($A['title'])* @param mixed key (string or integer)* @return boolean*/function offsetExists($offset){return array_key_exists($offset , get_object_vars($this));}
}// Create the object
$A = new Article('SPL Rocks','Joe Bloggs', 'PHP');// Check what it looks like
echo 'Initial State:<div>';
print_r($A);
echo '</div>';// Change the title using array syntax
$A['title'] = 'SPL _really_ rocks';// Try setting a non existent property (ignored)
$A['not found'] = 1;// Unset the author field
unset($A['author']);// Check what it looks like again
echo 'Final State:<div>';
print_r($A);
echo '</div>';

Serializable接口

接口摘要

Serializable {
/* 方法 */
abstract public string serialize ( void )
abstract public mixed unserialize ( string $serialized )
}

具体参考: http://php.net/manual/zh/class.serializable.php

简单的说,当实现了Serializable接口的类,被实例化后的对象,在序列化或者反序列化时都会自动调用类中对应的序列化或者反序列化方法;

class obj implements Serializable {private $data;public function __construct() {$this->data = "自动调用了方法:";}public function serialize() {$res = $this->data.__FUNCTION__;return serialize($res);}//然后上面serialize的值作为$data参数传了进来;public function unserialize($data) {$this->data = unserialize($res);}public function getData() {return $this->data;}
}$obj = new obj;
$ser = serialize($obj);
$newobj = unserialize($ser);//在调用getData方法之前其实隐式又调用了serialize与unserialize
var_dump($newobj->getData());

IteratorAggregate(聚合式迭代器)接口

类摘要

IteratorAggregate extends Traversable {/* 方法 */abstract public Traversable getIterator ( void )
}

Traversable作用为检测一个类是否可以使用 foreach 进行遍历的接口,在php代码中不能用。只有内部的PHP类(用C写的类)才可以直接实现Traversable接口;php代码中使用Iterator或IteratorAggregate接口来实现遍历。

实现了此接口的类,内部都有一个getIterator方法来获取迭代器实例;

class myData implements IteratorAggregate {private $array = [];const TYPE_INDEXED = 1;const TYPE_ASSOCIATIVE = 2;public function __construct( array $data, $type = self::TYPE_INDEXED ) {reset($data);while( list($k, $v) = each($data) ) {$type == self::TYPE_INDEXED ?$this->array[] = $v :$this->array[$k] = $v;}}public function getIterator() {return new ArrayIterator($this->array);}}$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',]/*,TYPE 1 or 2*/ );//↓↓ 遍历的时候其实就是遍历getIterator中实例的迭代器对象,要迭代的数据为这里面传进去的数据
foreach($obj as $key => $value) {var_dump($key, $value);echo PHP_EOL;
}

Countable 接口

类实现 Countable接口后,在count时以接口中返回的值为准.

//Example One, BAD :(
class CountMe{protected $_myCount = 3;public function count(){return $this->_myCount;}
}$countable = new CountMe();
echo count($countable); //result is "1", not as expected//Example Two, GOOD :)
class CountMe implements Countable{protected $_myCount = 3;public function count(){return $this->_myCount;}
}$countable = new CountMe();
echo count($countable); //result is "3" as expected 

ArrayObject类

简单的说该类可以使得像操作Object那样操作Array;

这是一个很有用的类;

/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');/*** create the array object ***/
$arrayObj = new ArrayObject($array);//增加一个元素
$arrayObj->append('dingo');//显示元素的数量
//echo $arrayObj->count();//对元素排序: 大小写不敏感的自然排序法,其他排序法可以参考手册
$arrayObj->natcasesort();//传入其元素索引,从而删除一个元素
$arrayObj->offsetUnset(5);//传入某一元素索引,检测某一个元素是否存在
if ($arrayObj->offsetExists(5))
{echo 'Offset Exists<br />';
}//更改某个元素的值
$arrayObj->offsetSet(3, "pater");//显示某一元素的值
//echo $arrayObj->offsetGet(4);//更换数组,更换后就以此数组为对象
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
$arrayObj->exchangeArray($fruits);// Creates a copy of the ArrayObject.
$copy = $fruitsArrayObject->getArrayCopy();/*** iterate over the array ***/
for($iterator = $arrayObj->getIterator();/*** check if valid ***/$iterator->valid();/*** move to the next array member ***/$iterator->next())
{/*** output the key and current array value ***/echo $iterator->key() . ' => ' . $iterator->current() . '<br />';
}

SplObserver, SplSubject

这是两个专用于设计模式中观察者模式的类,会在后面的设计模式专题中详细介绍;

SplFileInfo

简单的说,该对象就是把一些常用的文件信息函数进行了封装,比如获取文件所属,权限,时间等等信息,具体参考:
http://php.net/manual/zh/class.splfileinfo.php

SplFileObject

SplFileObject类为操作文件提供了一个面向对象接口. 具体参考:http://php.net/manual/zh/class.splfileobject.php

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {}

转载于:https://www.cnblogs.com/nixi8/p/5281138.html

【SPL标准库专题(3)】 Classes相关推荐

  1. php+spl+栈,PHP SPL标准库之数据结构栈(SplStack)介绍

    PHP SPL标准库之数据结构栈(SplStack)介绍2020-06-13 22:01:42 栈(Stack)是一种特殊的线性表,因为它只能在线性表的一端进行插入或删除元素(即进栈和出栈) SplS ...

  2. php spl函数,PHP SPL标准库中的常用函数介绍

    这篇文章主要介绍了PHP SPL标准库中的常用函数介绍,本文着重讲解了spl_autoload_extensions().spl_autoload_register().spl_autoload()三 ...

  3. PHP 设计模式 笔记与总结(3)SPL 标准库

    SPL 库的使用(PHP 标准库) 1. SplStack,SplQueue,SplHeap,SplFixedArray 等数据结构类 ① 栈(SplStack)(先进后出的数据结构) index.p ...

  4. php标准库string,PHP中的一些标准库

    很多PHPer都不知道PHP有着自己的一些标准库,官网已经列出了SPL的PHP标准库 网址:php.net/spl 标准库中主要的一些数据结构 数据结构 名称 SplStack 栈 SplQueue ...

  5. php 查看spl,PHP使用标准库spl实现的观察者模式示例

    本文实例讲述了PHP使用标准库spl实现的观察者模式.分享给大家供大家参考,具体如下: 前面使用纯php实现了一个观察者模式(php观察者模式), 现在使用php标准库spl在次实现观察者模式,好处是 ...

  6. STM32标准库的引入视频课程-第3季第6部分-朱有鹏-专题视频课程

    STM32标准库的引入视频课程-第3季第6部分-1017人已学习 课程介绍         本课程是<朱有鹏老师单片机完全学习系列课程>第3季第6个课程,本课程详细讲解了STM32官方新标 ...

  7. Python标准库asyncio模块基本原理浅析

    Python标准库asyncio模块基本原理浅析 本文环境python3.7.0 asyncio模块的实现思路 当前编程语言都开始在语言层面上,开始简化对异步程序的编程过程,其中Python中也开始了 ...

  8. 后端返回number类型数据_【JavaScript 教程】标准库—Number 对象

    作者 | 阮一峰 1.概述 Number对象是数值对应的包装对象,可以作为构造函数使用,也可以作为工具函数使用. 作为构造函数时,它用于生成值为数值的对象. var n = new Number(1) ...

  9. Python学习笔记011_模块_标准库_第三方库的安装

    容器 -> 数据的封装 函数 -> 语句的封装 类 -> 方法和属性的封装 模块 -> 模块就是程序 , 保存每个.py文件 # 创建了一个hello.py的文件,它的内容如下 ...

  10. 对象数组参数_【JavaScript 教程】标准库—Array 对象

    作者 | 阮一峰 1.构造函数 Array是 JavaScript 的原生对象,同时也是一个构造函数,可以用它生成新的数组. var arr = new Array(2);arr.length // ...

最新文章

  1. 开源库nothings/stb的介绍及使用(图像方面)
  2. 《预训练周刊》第40期: 量子预训练、千层BERT与GPT
  3. wpf每隔一小时_包河区徐河排涝站24小时不间断运作 11座区管泵站全面应战保安澜...
  4. 【微信小程序】wx:for
  5. 《计算机科学概论(第12版)》—第0章0.3节学习大纲
  6. 硬核!这所大学包下高铁,接滞留湖北的学生返校!
  7. [leetcode] Single Number 查找数组中的单数
  8. linux docker自动启动,linux – Cron作业不能在Docker容器内自动运行
  9. 30篇记录==一个月了~
  10. 一个免费提升独立站转化率神器-tidio实时在线客服聊天工具
  11. excel处理html文件,html网页显示excel表格数据-html读取本地excel文件并展示
  12. centos下安装transmission下载工具
  13. ai人工智能电子计算机星际穿越,以智慧AI为眸,华为nova5系列带你来一场“星际穿越”...
  14. 记录TI电量计采集化学ID过程
  15. android10管理权限,Android 权限管理
  16. GN_2_使用GN编译自己写的程序
  17. 差钱吗?周杰伦线上演唱会没关打赏惹争议,看看同时直播的腾格尔
  18. codeforces 1244 C 数论
  19. 微信小程序外卖cps和cpa系统
  20. eclipse jdt.core(一)——简介

热门文章

  1. DNF怎么查看服务器状态,dnf显示服务器读取中进不去怎么办 dnf显示服务器读取中进不去解决方法...
  2. Android studio 设置默认打开项目,默认打开项目方式
  3. kafka的connect实现数据写入到kafka和从kafka写出
  4. [渝粤教育] 浙江大学 物理光学实验及仿真 参考 资料
  5. 软件类配置(二)【Windows中安装python、pycharm、opencv、anaconda】
  6. 一、RequireHttps
  7. intellij自动补全变量名和变量属性
  8. 使用系统定时器SysTick实现精确延时微秒和毫秒函数
  9. Android使用scrollview截取整个的屏幕并分享微信
  10. [bzoj1062] [NOI2008]糖果雨