Home >Backend Development >PHP Tutorial >Using Iterator, ArrayAccess and Countable in 24php

Using Iterator, ArrayAccess and Countable in 24php

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 09:01:381232browse

Iterators are often used by us to facilitate data management when reading large amounts of data in the database.

<?php
class Basket implements Iterator{
    private $fruits = array(&#39;apple&#39;, &#39;banna&#39;, &#39;pear&#39;, &#39;orange&#39;, &#39;watermelon&#39;);
    private $position = 0; 
    
    //返回当前的元素
    public function current(){
        return $this->fruits[$this->position];
    }
    //返回当前的键
    public function key(){
        return $this->position
    }
    //下移一个元素
    public function next(){
        ++$this->position;
    }
    
    //移动到第一个元素
    public function rewind(){
        $this->position = 0;
    }
    //判断后续是否还有元素
    public function valid(){
        return isset($this->fruits[$this->position+1]);
    }
    
}


Makes the data in the object accessible like an array

<?php
class obj implements ArrayAccess{
    private $container = array();

    public function __construct(){
        $this->container = array(
            "one" => 1,
            "two" => 2,
            "three" => 3
            
        );
    }
    
    //赋值
    public function offsetSet($offset, $value){
        if(is_null($offset)){
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }
    
    //某键是否存在
    public function offsetExists($offset){
        return isset($this->container[$offset]);
    }
    
    //删除键值
    public function offsetUnset($offset){
        unset($this->container[$offset]);
    }
    
    //获取键对应的值
    public function offsetGet($offset){
        return isset($this->container[$offset])?$this->container[$offset]:null;
    }
}

$obj = new obj();
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj['two'] = "A value";

var_dump($obj['two']);
echo $obj['two'];
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
var_dump($obj);

Makes the object count properties

<?php 
class Basket implements Countable{
    private $fruits = array(&#39;apple&#39;, &#39;banna&#39;, &#39;pear&#39;, &#39;orange&#39;, &#39;watermelon&#39;);
    public function count(){
        return count($this->fruits);
    }
}

$basket = new Basket();
echo count($basket);


The above introduces the use of Iterator, ArrayAccess and Countable in 24php, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn