php SPL标准库iterator和ArrayAccess的学习

最近在补充学习php基础的时候看到了spl的介绍,学习了一下iterator和arrayAccess的使用,iterator主要是对象的迭代,一般可以用在容器里面,或者工厂模式里面,最常见的应用场景就是laravel的容器了,arrayAccess也是这样的,那么我们接下来就看下他们是怎么使用的吧。
iterator简易demo如下:

<?php

class TestIterator implements Iterator
{
    private $arr = [];

    private $key = 0;

    public function __construct(array $arr)
    {
        $this->arr = $arr;
    }

    public function rewind()
    {
        echo __METHOD__.PHP_EOL;
        $this->key = 0;
    }

    public function current()
    {
        echo __METHOD__.PHP_EOL;
        return $this->arr[$this->key];
    }

    public function next()
    {
        echo __METHOD__.PHP_EOL;
        ++$this->key;
    }

    public function valid()
    {
        echo __METHOD__.PHP_EOL;
        return isset($this->arr[$this->key]);
    }

    public function key()
    {
        return $this->key.PHP_EOL;
    }
}

$test = new TestIterator(['apple','orange','banana']);
foreach ($test as $k => $v) {
    var_dump($v);
}
//输出为:
TestIterator::rewind
TestIterator::valid
TestIterator::current
/Users/icarus/Code/php/itertaor.php:46:
string(5) "apple"
TestIterator::next
TestIterator::valid
TestIterator::current
/Users/icarus/Code/php/itertaor.php:46:
string(6) "orange"
TestIterator::next
TestIterator::valid
TestIterator::current
/Users/icarus/Code/php/itertaor.php:46:
string(6) "banana"
TestIterator::next
TestIterator::valid

ArrayAccess示例demo如下:

<?php

class TestArrayAccess implements ArrayAccess
{
	private $arr = [];
	
	
	public function __construct(Array $arr)
	{
		$this->arr = $arr;
	}
	
	public function offsetExists($offset)
	{
		echo __METHOD__ . PHP_EOL;
		return isset($this->arr[$offset]);
		
	}
	
	public function offsetGet($offset)
	{
		echo __METHOD__.PHP_EOL;
		return $this->arr[$offset];
	}
	
	public function offsetSet($offset, $value)
	{
		echo __METHOD__.PHP_EOL;
		$this->arr[$offset] = $value;
	}
	
	public function offsetUnset($offset)
	{
		echo __METHOD__ .PHP_EOL;
		unset($this->arr[$offset]);
	}
	
}

$test = new TestArrayAccess(['person'=>'man','fruit'=>'apple']);
var_dump($test['person']);
var_dump($test['children']);
$test['hello'] ='world';
var_dump($test['hello']);

iteroatr是用来迭代用的,而arrayaccess主要是用来当作数组用的,组合起来更加强大,可以参考pimple项目。本文主要是用来记录和学习用的。

原文地址:https://www.cnblogs.com/ontheway1024/p/7295496.html