zoukankan      html  css  js  c++  java
  • PHP 的 ArrayAccess 接口像数组一样来访问你的 PHP 对象

    如果想让对象使用起来像一个 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() 方法。



  • 相关阅读:
    走线规范-标识
    python学习之网路操作
    python学习之函数
    RTT学习之软件包
    RT_THREAD之组件学习
    RT_THREAD之nano学习
    物联网相关的模块
    JavaScript学习笔记之二
    javascript完美实现图片拖动改变顺序
    响应式WEB设计的9项基本原则
  • 原文地址:https://www.cnblogs.com/catprayer/p/1837290.html
Copyright © 2011-2022 走看看