L'interface ArrayAccess

(PHP 5, PHP 7)

Introduction

Interface permettant d'accéder aux objets de la même façon que pour les tableaux.

Sommaire de l'Interface

ArrayAccess {
/* Méthodes */
abstract public offsetExists ( mixed $offset ) : bool
abstract public offsetGet ( mixed $offset ) : mixed
abstract public offsetSet ( mixed $offset , mixed $value ) : void
abstract public offsetUnset ( mixed $offset ) : void
}

Exemple #1 Exemple simple

<?php
class obj implements ArrayAccess {
    private 
$container = array();
    public function 
__construct() {
        
$this->container = array(
            
"un"    => 1,
            
"deux"  => 2,
            
"trois" => 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["deux"]));
var_dump($obj["deux"]);
unset(
$obj["deux"]);
var_dump(isset($obj["deux"]));
$obj["deux"] = "Une valeur";
var_dump($obj["deux"]);
$obj[] = 'Ajout 1';
$obj[] = 'Ajout 2';
$obj[] = 'Ajout 3';
print_r($obj);
?>

L'exemple ci-dessus va afficher quelque chose de similaire à :

bool(true)
int(2)
bool(false)
string(10) "Une valeur"
obj Object
(
    [container:obj:private] => Array
        (
            [un] => 1
            [trois] => 3
            [deux] => Une valeur
            [0] => Ajout 1
            [1] => Ajout 2
            [2] => Ajout 3
        )

)

Sommaire