php 常用的接口和函数

ArrayAccess

--- interface to provide accessing to objects as arrays 提供以数组形式访问对象的接口。

interface synopsis 接口需要实现下面几个方法

php 复制代码
interface ArrayAccess {
/* Methods */
public offsetExists(mixed $offset): bool
public offsetGet(mixed $offset): mixed
public offsetSet(mixed $offset, mixed $value): void
public offsetUnset(mixed $offset): void
}

basic usage 基础用法 实现访问数组的方式访问接口

php 复制代码
<?php
class Obj implements ArrayAccess {
    public $container = [
        "one"   => 1,
        "two"   => 2,
        "three" => 3,
    ];

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

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

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

    public function offsetGet($offset): mixed {
        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);
?>

the above example will output something similar to : 输出结果

php 复制代码
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
        )

)

php官网ArrayAccess

相关推荐
漏刻有时4 小时前
PHP GeoJSON转PNG地图渲染程序开发笔记、源码解读、问题复盘与整改方案
android·笔记·php
always_TT6 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
Immortal__y9 小时前
Upload-Labs 关卡防御方式
php
JonLee202011 小时前
适配 Yii 3.0,php-casbin/yii-permission 3.0 正式发布
安全·php·rbac·yii·权限·casbin
QH1392923188013 小时前
# R&S ZNB43 ZNA43 ZNA67矢量网络分析仪
开发语言·网络·php
名字还没想好☜15 小时前
Python concurrent.futures 实战:用 ThreadPoolExecutor 并发处理 + as_completed 收结果
数据库·python·php·并发
风样滴男人哟16 小时前
PHP特性之反射类ReflectionClass机制
android·开发语言·php
nvd1116 小时前
GCP L4 Passthrough 负载均衡器“假死超时”深度排查复盘
运维·php·负载均衡
2601_9657984718 小时前
ForumLab Review: Fast PHP Script for SEO Forum Sites
android·adb·php
姜太小白1 天前
【Linux】df -h 卡住问题的通用排查与解决方案总结
linux·运维·php