The ArrayAccess interface

(PHP 5, PHP 7, PHP 8)

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

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
}

Example #1 Basic usage

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

The above example will output something similar to:

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
        )

)

Table of Contents

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe
There are no comments available yet.

News for PHP developers: Laravel 11 release

On March 12, 2024, the long-awaited version 11 of the Laravel framework was released, bringing with it a number of exciting new features and improvements for the PHP development community. ...

Mike94

Autor : Mike94
Category: PHP Magazin

Technical SEO remains relevant

Technical SEO - What is it anyway? Technical SEO refers to the optimization of the technical aspects of your website. The goal is clear! ...

admin

Autor : admin
Category: SEO & Online-Marketing

What's new in PHP 8.2.10

PHP 8.2.10 is one of the latest versions of PHP, which brings a number of improvements and new features. In this article we will discuss some of the outstanding new features and improvements in this version. ...

admin

Autor : admin
Category: Software-Updates

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial