• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

24php中使用Iterator,ArrayAccess和Countable

php 搞代码 3年前 (2022-01-23) 22次浏览 已收录 0个评论

迭代器往往被我们用来在数据库中读取大量的数据时方便数据的管理。

<?phpclass Basket implements Iterator{    private $fruits = array('apple', 'banna', 'pear', 'orange', 'watermelon');    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]);    }    }

使对象中的数据可以像数组一样访问

<?phpclass 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);

使对象可以对属性进行计数

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

以上就介绍了24php中使用Iterator,ArrayA/本文来源gao@!dai!ma.com搞$$代^@码5网@搞代gaodaima码ccess和Countable,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:24php中使用Iterator,ArrayAccess和Countable

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址