首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

ArrayAccess (interface)

介绍

(PHP 5 >= 5.0.0, PHP 7)

提供数组访问对象的接口。

界面简介

ArrayAccess {

/* Methods */

代码语言:javascript
复制
abstract public boolean offsetExists ( mixed $offset )
代码语言:javascript
复制
abstract public mixed offsetGet ( mixed $offset )
代码语言:javascript
复制
abstract public void offsetSet ( mixed $offset , mixed $value )
代码语言:javascript
复制
abstract public void offsetUnset ( mixed $offset )

}

示例#1基本用法

代码语言:javascript
复制
<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

上面的例子会输出类似于:

代码语言:javascript
复制
bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

目录

  • ArrayAccess::offsetExists - 是否存在偏移量
  • ArrayAccess::offsetGet - 要检索的偏移量
  • ArrayAccess::offsetSet - 为指定的偏移量分配一个值
  • ArrayAccess::offsetUnset - 取消偏移量

← Throwable::__toString

ArrayAccess::offsetExists →

扫码关注腾讯云开发者

领取腾讯云代金券