php 的arrayaccess抽象类的使用

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

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

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

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

案例输出

php 的arrayaccess抽象类的使用_第1张图片
输出结果

你可能感兴趣的:(php 的arrayaccess抽象类的使用)