跳到主要内容
PHP

ArrayAccess(数组式访问接口) 实现数据集数组式访问

管

管理员

https://www.php.net/manual/zh/class.arrayaccess.php

2022年09月02日 1,118 次阅读
本页目录

提供像访问数组一样访问对象的能力的接口。

接口摘要

 
interface ArrayAccess {
/* 方法 */
public offsetExists(mixed $offset): bool
public offsetGet(mixed $offset): mixed
public offsetSet(mixed $offset, mixed $value): void
public offsetUnset(mixed $offset): void
}
 

 

<?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);
?>

 

Related

相关文章

同分类文章 →
2026年07月11日 PHP

laravel什么样的方法适合放在模型中?什么适合用专门的服务类? cachedFavIds适合放在模型中吗?

一、适合放在模型中的方法Laravel 采用 ActiveRecord 风格,模型本身就是&quot;数据 + 围绕该数据的操作&quot;的载体。以下几类方法适合放模型: 关联关系:belongsTo、morphTo、hasMany 等。如 UserFav::userfavable()、UserFav::us

2026年04月13日 PHP

Vue3 静态文件放在同域名 Laravel 项目下

核心思路是:Vue3 构建后的静态文件放到 Laravel 的 public/ 目录下,通过 Laravel 路由的 catch-all 机制让 SPA 的前端路由正常工作。方案说明以 xx.com/admin 为例,整体架构如下:请求流程:xx.com/admin/* → Laravel

2025年08月18日 PHP

Laravel Eloquent 中可以通过静态方式调用的方法

在 Laravel Eloquent 中,可以通过静态方式调用的方法包括:1. 查询作用域 (Scopes)// 可以静态调用UserComment::active()-&gt;get();UserComment::where(&#039;status&#039;, 1)-&gt;first();2. Eloquent 内置的查询方法UserComment::fi

WeChat

扫码加我微信

微信二维码