php语言 百分网手机站

PHP的ArrayAccess接口

时间:2020-08-07 19:43:49 php语言 我要投稿

PHP的ArrayAccess接口

  如果想让对象使用起来像一个 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漏洞09-22

Java接口介绍12-08

硬盘的接口类型10-09

CPU的接口类型10-07

php学习之php配置09-09

PHP的优点09-27

PHP的缺点09-27

PHP的变量09-20

介绍Java array接口11-29

Java中接口的知识汇总12-01