【SPL标准库专题(3)】 Classes
我把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 {}
												
											【SPL标准库专题(3)】 Classes的更多相关文章
- 【SPL标准库专题(1)】 SPL简介
		
什么是SPL SPL是Standard PHP Library(PHP标准库)的缩写. 根据官方定义,它是"a collection of interfaces and classes th ...
 - 【SPL标准库专题(2)】 Iterator
		
Iterator界面 本段内容来自阮一峰老师再加自己的部分注解 SPL规定,所有部署了Iterator界面的class,都可以用在foreach Loop中.Iterator界面中包含5个必须部署的方 ...
 - 【SPL标准库专题(10)】SPL Exceptions
		
嵌套异常 了解SPL异常之前,我们先了解一下嵌套异常.嵌套异常顾名思义就是异常里面再嵌套异常,一个异常抛出,在catch到以后再抛出异常,这时可以通过Exception基类的getPrevious方法 ...
 - 【SPL标准库专题(9)】 Datastructures:SplObjectStorage
		
PHP SPL SplObjectStorage是用来存储一组对象的,特别是当你需要唯一标识对象的时候. PHP SPL SplObjectStorage类实现了Countable,Iterator, ...
 - 【SPL标准库专题(8)】 Datastructures:SplFixedArray
		
SplFixedArray主要是处理数组相关的主要功能,与普通php array不同的是,它是固定长度的,且以数字为键名的数组,优势就是比普通的数组处理更快. 类摘要 SplFixedArray im ...
 - 【SPL标准库专题(7)】 Datastructures:SplHeap & SplMaxHeap & SplMinHeap
		
堆(Heap)就是为了实现优先队列而设计的一种数据结构,它是通过构造二叉堆(二叉树的一种)实现.根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆.二叉堆还常用于排序(堆排序). 类摘 ...
 - 【SPL标准库专题(6)】 Datastructures:SplPriorityQueue
		
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头取出.在优先队列中,元素被赋予优先级.当访问元素时,具有最高优先级的元素最先取出.优先队列具有最高级先出 (largest-in,fir ...
 - 【SPL标准库专题(5)】 Datastructures:SplStack & SplQueue
		
这两个类都是继承自SplDoublyLinkedList,分别派生自SplDoublyLinkedList的堆栈模式和队列模式:所以放在一起来介绍: 堆栈SplStack # 类摘要 SplStack ...
 - 【SPL标准库专题(4)】 Datastructures:SplDoublyLinkedList
		
简述 双链表是一种重要的线性存储结构,对于双链表中的每个节点,不仅仅存储自己的信息,还要保存前驱和后继节点的地址. 类摘要 SplDoublyLinkedList implements Iterato ...
 
随机推荐
- Editplus php
			
一.配置PHP帮助手册 1.打开Editplus,[工具]-->[配置用户工具],在[添加工具]子菜单下选择[HTML帮助(*.chm)(T)],文件路径选择php的chm帮助文件路径. 这样在 ...
 - Visual Studio最好用的快捷键(你最喜欢哪个)
			
每次在网上搜关于VS有哪些常用快捷键的时候,出来的永远是一串长的不能再长的列表,完全没体现出“常用”二字,每次看完前面几个就看不下去了,相信大家都 有这种感觉.其实我们平时用的真的只有很少的一部分,借 ...
 - Netty 核心组件 Pipeline 源码分析(二)一个请求的 pipeline 之旅
			
目录大纲: 前言 针对 Netty 例子源码做了哪些修改? 看 pipeline 是如何将数据送到自定义 handler 的 看 pipeline 是如何将数据从自定义 handler 送出的 总结 ...
 - 并发编程之 Java 三把锁
			
前言 今天我们继续学习并发.在之前我们学习了 JMM 的知识,知道了在并发编程中,为了保证线程的安全性,需要保证线程的原子性,可见性,有序性.其中,synchronized 高频出现,因为他既保证了原 ...
 - .33-浅析webpack源码之doResolve事件流(5)
			
file => FileExistsPlugin 这个事件流快接近尾声了,接下来是FileExistsPlugin,很奇怪的是在最后才来检验路径文件是否存在. 源码如下: FileExistsP ...
 - Spring学习之路-从放弃到入门
			
AOP:方法拦截器 IOC:类管理容器 主要讲讲这一天看Spring视频学到的东西,以下的叫法全是自创的. 1.类实例管理容器 关于Spring,首先是对类的管理,在常规情况,生成一个类需要调用new ...
 - Bower前端模块管理器
			
cnpm install bower -g 安装bower bower install jquery //bower会自动去网上找到最新版本的jquery bower uninstall jquery ...
 - C# 金额转中文大写
			
今天看到一个库是把金额转中文大写,看起来很容易,所以我就自己写了 创建的项目是创建一个 dot net core 的项目,实际上这个项目可以创建为 Stand 的. 首先创建类,这个类的构造传入一个 ...
 - golang中的 time 常用操作
			
时间戳 时间戳 (例如: 1554714009) time.now().Unix() 格式时间 (例如: 2019-04-08 17:00:09) time.Now().Format("20 ...
 - 转载--Json转换
			
JSON的全称是”JavaScript Object Notation”,意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式.XML也是一种数据交换格式,为什么没 ...