云迈博客

您现在的位置是:首页 > 灌水专栏 > 正文

灌水专栏

PHP预定义接口ArrayAccess使用记录

林恒2021-09-28灌水专栏300
通常情况下,我们会看到this['name']这样的用法,但是我们知道,$this是一个对象,是如何使用数组方式访问的?答案就是实现了数据组访问接口ArrayAccess,具体代码如下c

通常情况下,我们会看到 this [‘name’] 这样的用法,但是我们知道,$this 是一个对象,是如何使用数组方式访问的?答案就是实现了数据组访问接口 ArrayAccess,具体代码如下

class Index
{
    public function index()
    {
        $test = new Test();
        var_dump(isset($test['title'])); ##bool(true)
        var_dump($test['a'] = 123);    ##int(123)
        echo $test['a'];  ##123
    }
}
<?php

class Test implements \ArrayAccess
{

    public $arr = [
        'title' => 'test'
    ];

    public function offsetUnset($offset)
    {
        echo "offsetUnset" . PHP_EOL;
        unset($this->arr[$offset]);
    }

    public function offsetExists($offset): bool
    {
        echo "offsetExists" . PHP_EOL;
        return isset($this->arr[$offset]);
    }

    public function offsetGet($offset)
    {
        echo "offsetGet" . PHP_EOL;
        return $this->arr[$offset] ?? "";
    }

    public function offsetSet($offset, $value)
    {
        echo "offsetSet" . PHP_EOL;
        $this->arr[$offset] = $value;
    }
}

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~