哪个 PHP SPL 接口(interface)允许对象执行此操作:
$object->month = 'january';
echo $object['month']; // january
$record['day'] = 'saturday';
echo $record->day; // saturday
例如例如在 Doctrine (Doctrine_Record) 这样的库中
我该如何实现?我试过使用 ArrayObject,但它们的行为并不像我想象的那样。
即
$object = new ArrayObject();
$object['a'] = 'test';
$object['a'] == $object->a; // false
编辑:
我尝试了一个我称之为 Arrayable 的准系统实现。
class Arrayable implements ArrayAccess
{
protected $container = array();
# implement ArrayAccess methods to allow array notation
# $object = new Arrayable();
# $object['value'] = 'some data';
function offsetExists($offset)
{
return isset($this->container[$offset]);
}
function offsetGet($offset)
{
return $this->container[$offset];
}
function offsetSet($offset, $value)
{
$this->container[$offset] = $value;
}
function offsetUnset($offset)
{
unset($this->container[$offset]);
}
# now, force $object->value to map to $object['value']
# using magic methods
function __set($offset, $value)
{
$this->offsetSet($offset, $value);
}
function __get($offset)
{
return $this->offsetGet($offset);
}
}
最佳答案
参见 sourcecode for Doctrine_Record
abstract class Doctrine_Record
extends Doctrine_Record_Abstract
implements Countable, IteratorAggregate, Serializable
abstract class Doctrine_Record_Abstract extends Doctrine_Access
最后是 Doctrine_Access
abstract class Doctrine_Access
extends Doctrine_Locator_Injectable
implements ArrayAccess
来自文档 block
Provides array access and property overload interface for Doctrine subclasses
实现 ArrayAccess 的对象必须具有这些方法
abstract public boolean offsetExists ( mixed $offset );
abstract public mixed offsetGet ( mixed $offset );
abstract public void offsetSet ( mixed $offset , mixed $value );
abstract public void offsetUnset ( mixed $offset );
PHP 手册(上面链接)中有一个基本用法示例
关于php - 哪个 PHP 接口(interface)允许使用数组表示法访问对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312833/