Обращение к классу как к массиву
<?php
// Чтобы работать с классом как с массивом,
// нужно реализовать интерфейс ArrayAccess
class MyArray implements ArrayAccess
{
/**
* Здесь будут храниться данные класса-массива
*
* @var array
*/
protected $_data = array();
/*
* Реализация интерфейса ArrayAccess
*/
/**
* Установить значение ключа $offset в $value
*
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
$this->_data[$offset] = $value;
}
/**
* Проверка существования ключа $offset
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->_data[$offset]);
}
/**
* Удаление улюча $offset
*
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset)
{
unset($this->_data[$offset]);
}
/**
* Получить значение ключа $offset
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->_data[$offset]) ? $this->_data[$offset] : null;
}
/**
* Остальные методы
*/
public function hello()
{
echo "Hello, world!";
}
}
$myarr = new MyArray();
$myarr[0] = 'value 0';
$myarr['foo'] = 'bar';
$myarr->hello();
echo '<pre>';
print_r($myarr);
echo '</pre>';