php 的arrayaccess抽象类的使用

php中有一个arrayaccess抽象类其中有四个抽象方法

  • offsetSet($offset, $value)
  • offsetGet($offset)
  • offsetExists($offset)
  • offsetUnset($offset)

实现arrayaccess后可对对象进行数组式的操作,上代码:

<?php
class async implements arrayaccess {
    private $func = false;
    private $arg = false;
    private $data = false;

    public function __construct($func, $arg = []) {
        $this->func = $func;
        $this->arg = $arg;
    }

    public function __call($f, $a = []) {
        if ($this->data === false) {
            $this->data = call_user_func_array($this->func, $this->arg);
        }
        return call_user_func_array([$this->data, $f], $a);
    }

    public function __get($name) {
        if ($this->data === false) {
            $this->data = call_user_func_array($this->func, $this->arg);
        }
        return $this->data->$name;
    }

    public function offsetGet($offset) {
        if ($this->data === false) {
            $this->data = call_user_func_array($this->func, $this->arg);
        }

        if (isset($this->data[$offset])) {
            return $this->data[$offset];
        }

        throw new Exception($offset,1);
    }

    public function offsetSet($offset, $value) {
        if ($this->data === false) {
            $this->data = call_user_func_array($this->func, $this->arg);
        }
        $this->data[$offset] = $value;
    }

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

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

class myclass {
    public $arg1 = 'hello';
    public $arg2 = 'world';

    function __construct($other) {
        $this->other = $other;
    }

    public function say () {
        echo $this->arg1 . $this->arg2;
    }
}

$asyncobj = new async(function($arg){return new myclass($arg);}, ['我是一个测试参数']);
$asyncarray = new async(function(){return array();});
$asyncarray['myarg'] = 'add new argument;';
echo $asyncarray['myarg'];
$asyncarray->myarg = 'outer args';
echo $asyncarray->myarg;

这个类既继承了arrayaccess,也封装了前面 介绍的延迟加载,取决于你传入的参数;

案例输出

输出结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,848评论 25 709
  • 一七年十月中旬,仔细想来也不过刚开学一个月而已,感觉自己好像一下子就从懵懵懂懂、不知所谓过度到了瞻前顾后、谨慎担忧...
    诉旧阅读 276评论 0 0
  • ES6变量的两种命名方式# es6是ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言...
    燕妮666_阅读 2,032评论 3 5