php 的arrayaccess抽象类的使用

96
hopevow
2016.10.20 11:02* 字数 83

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,也封装了前面 介绍的延迟加载,取决于你传入的参数;

案例输出

输出结果
web编程之路
Web note ad 1