[ create a new paste ] login | about

Link: http://codepad.org/7oxYrB9j    [ raw code | output | fork ]

PHP, pasted on Oct 11:
<?php

class strKey implements ArrayAccess
{
    private $arr;
    public function __construct(&$array)
    {
        $this->arr = &$array;
    }

    public function offsetExists($offset)
    {
        foreach ($this->arr as $key => $value)
        {
            if ($key == $offset)
            {
                return true;
            }
        }
        return false;
    }

    public function offsetGet($offset)
    {
        foreach ($this->arr as $key => $value)
        {
            if ($key == $offset)
            {
                return $value;
            }
        }
        return null;
    }

    public function offsetSet($offset, $value)
    {
        foreach($this->arr as $key => &$thevalue)
        {
            if ($key == $offset)
            {
                $thevalue = $value;
                return;
            }
        }

        // if $offset is *not* present...
        if ($offset === null)
        {
            $this->arr[] = $value;
        }
        else
        {
            // this won't work with string keys
            $this->arr[$offset] = $value;
        }
    }

    // can't implement this
    public function offsetUnset($offset)
    {
        foreach ($this->arr as $key => &$value)
        {
            if ($key == $offset)
            {
                //$value = null;
            }
        }
    }
}

$obj = new stdClass;
$obj->{10} = 'Thing';

$objArray = (array) $obj;
var_dump($objArray);

$b = new strKey($objArray);

echo $b['10'] . "\n"; // Thing
$b['10'] = 'Something else';

// because the classes works with a reference to the original array,
// this will give us a modified array:
var_dump($objArray); 


Output:
1
2
3
4
5
6
7
8
9
array(1) {
  ["10"]=>
  string(5) "Thing"
}
Thing
array(1) {
  ["10"]=>
  string(14) "Something else"
}


Create a new paste based on this one


Comments: