php - 哪个 PHP 接口(interface)允许使用数组表示法访问对象的属性?

标签 php arrays spl arrayobject

哪个 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); 
    }
}

最佳答案

ArrayAccess

参见 sourcecode for Doctrine_Record

abstract class Doctrine_Record 
    extends Doctrine_Record_Abstract 
    implements Countable, IteratorAggregate, Serializable

Doctrine_Record_Abstract

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/

相关文章:

php - 在 php 中将年添加到今天的日期

javascript - 使用 javascript 查询结果作为 HTML 表单的输入

php - 单元测试 Laravel 5 时无法测试重定向

java - System.arraycopy() 具有原始和对象引用的浅拷贝或深拷贝

php - 如何在使用 RecursiveArrayIterator 时更改数组键和值?

php - 涉及 SplEnum 时遍历 PHP 类变量

c# - 存储经过良好散列处理的密码及其散列方法是否很危险?

javascript - 拆分数组仍然是一个项目的数组而不是一个字符串

javascript - JS中agGrid显示二维数组

php - 使用 PHP 迭代器