PYTHON The ArrayAccess interface

is this article helpful?
|
Python replacement for PHP's The ArrayAccess interface [ edit | history ]
class ArrayAccess(object):
def __getitem__(self, key):
return self.container

def __setitem__(self, key, value):
self.container=value

def __delitem__(self, key, value):
del self.container

PHP The ArrayAccess interface

PHP original manual for The ArrayAccess interface [ show | php.net ]

The ArrayAccess interface

Introduction

Interface to provide accessing objects as arrays.

Class synopsis

ArrayAccess
ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( string $offset )
abstract public mixed offsetGet ( string $offset )
abstract public void offsetSet ( string $offset , string $value )
abstract public void offsetUnset ( string $offset )
}

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) {
        
$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"]);

?>

The above example will output something similar to:

bool(true)
int(2)
bool(false)
string(7) "A value"

Table of Contents