编程

PHP数组式访问接口 ArrayAccess,Coutable接口,迭代器接口Iterator

917 2021-12-20 05:24:32

1.ArrayAccess提供像访问数组一样访问对象的能力的接口。

接口摘要 

interface ArrayAccess {
	/* 方法 */
	public offsetExists(mixed $offset): bool //检查一个偏移位置是否存在
	public offsetGet(mixed $offset): mixed //获取一个偏移位置的值
	public offsetSet(mixed $offset, mixed $value): void //设置一个偏移位置的值
	public offsetUnset(mixed $offset): void //复位一个偏移位置的值
}

示例:

class MyCollection implements ArrayAccess {
    private $data = [];

    public function __construct(Array $array) {
        $this->data = $array
    }
    
    public function make(Array $array) {
        $this->data = $array
    }
    

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }
}

2. Countable接口:继承Countable接口的类可以使用count() 函数

接口摘要

interface Countable {
	/* Methods */
	public count(): int
}

示例:

class MyCollection implements ArrayAccess {
    private $data = [];

    public function __construct(Array $array) {
        $this->data = $array;
    }
    
    public function make(Array $array) {
        $this->data = $array;
        return $this;
    }
    
    public funtion count(){
    	return count($this->data);
    }

 
}

3. Iterator (迭代器接口)

如果你想让你的对象能够像数组那样使用 foreach 将其中的某些数据循环出来,你可以将类实现 Iterator接口

接口摘要

interface Iterator extends Traversable {
	/* 方法 */
	public current(): mixed //返回当前元素
	public key(): mixed //返回当前元素的键
	public next(): void //向前移动到下一个元素
	public rewind(): void //返回到迭代器的第一个元素
	public valid(): bool //检查当前位置是否有效
}

示例:

<?php
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );  

    public function __construct() {
        $this->position = 0;
    }

    public function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    public function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    public function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    public function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    public function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

参考Laravel中Collection的实现方式

class Collection implements ArrayAccess, Enumerable
{
	//...
}

interface Enumerable extends Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
{
	...
}