• 技术文章 >后端开发 >php教程

    代码详解php中的ArrayAccess接口

    伊谢尔伦伊谢尔伦2017-06-29 09:47:26原创557
    slim中的依赖注入基于pimple,于是又去学习了一下pimple。 对比之前自己写的依赖注入类,pimple有一个很新鲜的用法,不是采用

    $container->session_storage = function ($c) {
        return new $c['session_storage_class']($c['cookie_name']);
    };

    而是以数组方式进行注入:

    $container['session_storage'] = function ($c) {
        return new $c['session_storage_class']($c['cookie_name']);
    };

    看源码时才发现原来诀窍就在php5提供的ArrayAccess接口上。
    官方定义:提供像访问数组一样访问对象的能力的接口。
    该接口主要定义了四个抽象方法:

    abstract public boolean offsetExists ( mixed $offset ) #检查数据是否存在
    abstract public mixed offsetGet ( mixed $offset )      #获取数据
    abstract public void offsetSet ( mixed $offset , mixed $value )     #设置数据   
    abstract public void offsetUnset ( mixed $offset ) #删除数据

    如果想让对象使用起来像一个 PHP 数组,那么我们需要实现 ArrayAccess 接口

    代码如下:

    interface ArrayAccess 
    boolean offsetExists($index) 
    mixed offsetGet($index) 
    void offsetSet($index, $newvalue) 
    void offsetUnset($index)


    下面的例子展示了如何使用这个接口,例子并不是完整的,但是足够看懂,:->

    代码如下:

    <?php 
    class UserToSocialSecurity implements ArrayAccess 
    { 
    private $db;//一个包含着数据库访问方法的对象 
    function offsetExists($name) 
    { 
    return
     $this->db->userExists($name); 
    } 
    function offsetGet($name) 
    { 
    return $this->db->getUserId($name); 
    } 
    function offsetSet($name, $id) 
    { 
    $this->db->setUserId($name, $id); 
    } 
    function offsetUnset($name) 
    { 
    $this->db->removeUser($name); 
    } 
    } 
    $userMap = new UserToSocialSecurity(); 
    print "John's ID number is " . $userMap['John']; 
    ?>


    实际上,当 $userMap['John'] 查找被执行时,PHP 调用了 offsetGet() 方法,由这个方法再来调用数据库相关的 getUserId() 方法。

    以上就是代码详解php中的ArrayAccess接口的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:ArrayAccess php 接口
    上一篇:php面向对象中的抽象类、对象接口、instanceof 和契约式编程教程 下一篇:php面向对象的接口技术实例详解
    大前端线上培训班

    相关文章推荐

    • PHP中的命名空间定义与使用(实例详解)• PHP中clone关键字和__clone()方法的使用(实例详解)• 带你分清类中的构造函数与析构函数• 五分钟带你了解PHP中的魔术方法(实例详解)• 怎样去搞定PHP类的继承?(总结分享)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网