【php语法】实现ArrayAccess接口,以数组的形式访问对象

ArrayAccess

简介:

是php Spl中的一个接口,提供像访问数组一样访问对象的能力。

摘要:

 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 接口使对象可以像数组一样被访问
 */
class Configuration implements ArrayAccess
{
   static private $config=null;
   private $configarray = array(
   		'firstName' => 'kai',
   		'secondName' => 'xinxin',
   		'age' => 24
   	);

   private function __construct(){}
   public static function instance()
   {
       if (self::$config == null)
       {
           self::$config = new Configuration();
       }
       return self::$config;
   }

   /**
    * [字段是否存在]
    * @param  [string] $index [字段名]
    * @return [boolean]        [字段是否存在]
    */
   function offsetExists($index)
   {
       return isset($this->configarray[$index]);
   }
   /**
    * [获取字段]
    * @param  [string] $index [字段名]
    * @return [string]        [字段值]
    */
   function offsetGet($index) {
       return $this->configarray[$index];
   }
   /**
    * [设置字段]
    * @param  [string] $index    [字段名]
    * @param  [string] $newvalue [字段值]
    */
   function offsetSet($index, $newvalue) {
       $this->configarray[$index] = $newvalue;
   }
   /**
    * [删除字段]
    * @param  [string] $index [字段名]
    */
   function offsetUnset($index) {
       unset($this->configarray[$index]);
   }
}

$config = Configuration::instance();
print $config["firstName"];


link:   ArrayAccess
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值