laravel学习之ArrayAccess

最近在学习laravel在,顺着流程看下去发现了一个比较奇怪的调用方法,在

registerBaseServiceProviders()
的注册路由的服务提供器时
$this->app['router'] = $this->app->share(function ($app) {
    return new Router($app['events'], $app);
});

 

这里找了好久没有找到变量$this->app,断点进去后发现原来是调用了spl库里面的ArrayAccess接口,这个接口可以令对象像数组一样访问而且通过重写方法可以加上自己的逻辑,以下就是我了解这个接口的笔记。
class arr implements ArrayAccess
{
    public $a = array();

    public function offsetExists($offset)//看数据是否存在
    {
        // TODO: Implement offsetExists() method.
        echo "判断存在";
    }

    public function offsetGet($offset)//获取数据
    {
        // TODO: Implement offsetGet() method.
        echo "<br>";
        echo "获取数据";
        echo "<br>";

    }

    public function offsetSet($offset, $value)//设置数据
    {
        // TODO: Implement offsetSet() method.
        echo "设置数据";
        echo "<br>";
    }

    public function offsetUnset($offset)//删除数据
    {
        // TODO: Implement offsetUnset() method.
        echo "删除数据";
        echo "<br>";
    }

}

$a = new arr();
$a['name'] = 'aaa';//调用offsetSet,输出设置数据

if (isset($a['name'])) {}//offsetExists,输出判断存在

echo $a['name'];//offsetGet,输出获取数据

unset($a['name']);//offsetUnset,输出删除数据

 

posted @ 2017-05-08 22:47  Gikkson  阅读(228)  评论(0编辑  收藏  举报