[关闭]
@a5635268 2016-02-20T13:41:49.000000Z 字数 5682 阅读 993

【SPL标准库专题(3)】 Classes

SPL


我把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. 复位一个偏移位置的值
  1. /**
  2. * A class that can be used like an array
  3. */
  4. class Article implements ArrayAccess{
  5. public $title;
  6. public $author;
  7. public $category;
  8. function __construct($title , $author , $category){
  9. $this->title = $title;
  10. $this->author = $author;
  11. $this->category = $category;
  12. }
  13. /**
  14. * Defined by ArrayAccess interface
  15. * Set a value given it's key e.g. $A['title'] = 'foo';
  16. * @param mixed key (string or integer)
  17. * @param mixed value
  18. * @return void
  19. */
  20. function offsetSet($key , $value){
  21. if (array_key_exists($key , get_object_vars($this))) {
  22. $this->{$key} = $value;
  23. }
  24. }
  25. /**
  26. * Defined by ArrayAccess interface
  27. * Return a value given it's key e.g. echo $A['title'];
  28. * @param mixed key (string or integer)
  29. * @return mixed value
  30. */
  31. function offsetGet($key){
  32. if (array_key_exists($key , get_object_vars($this))) {
  33. return $this->{$key};
  34. }
  35. }
  36. /**
  37. * Defined by ArrayAccess interface
  38. * Unset a value by it's key e.g. unset($A['title']);
  39. * @param mixed key (string or integer)
  40. * @return void
  41. */
  42. function offsetUnset($key){
  43. if (array_key_exists($key , get_object_vars($this))) {
  44. unset($this->{$key});
  45. }
  46. }
  47. /**
  48. * Defined by ArrayAccess interface
  49. * Check value exists, given it's key e.g. isset($A['title'])
  50. * @param mixed key (string or integer)
  51. * @return boolean
  52. */
  53. function offsetExists($offset){
  54. return array_key_exists($offset , get_object_vars($this));
  55. }
  56. }
  57. // Create the object
  58. $A = new Article('SPL Rocks','Joe Bloggs', 'PHP');
  59. // Check what it looks like
  60. echo 'Initial State:<div>';
  61. print_r($A);
  62. echo '</div>';
  63. // Change the title using array syntax
  64. $A['title'] = 'SPL _really_ rocks';
  65. // Try setting a non existent property (ignored)
  66. $A['not found'] = 1;
  67. // Unset the author field
  68. unset($A['author']);
  69. // Check what it looks like again
  70. echo 'Final State:<div>';
  71. print_r($A);
  72. echo '</div>';

Serializable接口

接口摘要

  1. Serializable {
  2. /* 方法 */
  3. abstract public string serialize ( void )
  4. abstract public mixed unserialize ( string $serialized )
  5. }

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

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

  1. class obj implements Serializable {
  2. private $data;
  3. public function __construct() {
  4. $this->data = "自动调用了方法:";
  5. }
  6. public function serialize() {
  7. $res = $this->data.__FUNCTION__;
  8. return serialize($res);
  9. }
  10. //然后上面serialize的值作为$data参数传了进来;
  11. public function unserialize($data) {
  12. $this->data = unserialize($res);
  13. }
  14. public function getData() {
  15. return $this->data;
  16. }
  17. }
  18. $obj = new obj;
  19. $ser = serialize($obj);
  20. $newobj = unserialize($ser);
  21. //在调用getData方法之前其实隐式又调用了serialize与unserialize
  22. var_dump($newobj->getData());

IteratorAggregate(聚合式迭代器)接口

类摘要

  1. IteratorAggregate extends Traversable {
  2. /* 方法 */
  3. abstract public Traversable getIterator ( void )
  4. }

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

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

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

Countable 接口

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

  1. //Example One, BAD :(
  2. class CountMe{
  3. protected $_myCount = 3;
  4. public function count(){
  5. return $this->_myCount;
  6. }
  7. }
  8. $countable = new CountMe();
  9. echo count($countable); //result is "1", not as expected
  10. //Example Two, GOOD :)
  11. class CountMe implements Countable{
  12. protected $_myCount = 3;
  13. public function count(){
  14. return $this->_myCount;
  15. }
  16. }
  17. $countable = new CountMe();
  18. echo count($countable); //result is "3" as expected

ArrayObject类

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

这是一个很有用的类;

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

SplObserver, SplSubject

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

SplFileInfo

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

SplFileObject

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

  1. SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {}
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注