2

オブジェクトがこれを行うことを許可する PHP SPL インターフェイスは次のうちどれですか。

$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); 
    }
}
4

5 に答える 5

4

アレイアクセスです

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

DocBlock から

Doctrine サブクラスに配列アクセスとプロパティ オーバーロード インターフェイスを提供します


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 マニュアル (上記リンク) に基本的な使用例があります。

于 2010-02-22T17:49:56.673 に答える
3

ここでは2つの異なるものを使用しています:

の ArrayAccess インターフェイス$a[key]http://php.net/manual/en/language.oop5.overloading.php$a->key

何が起こるかは

$a[key]$a->offsetGet(key)(ArrayAccess から継承された)$a->keyを呼び出し、$a->__get(key)または$a->__set(key, val)(のようなコンテキストで$a->key = val) を呼び出します。

于 2010-02-22T17:52:37.953 に答える
0

オブジェクトと配列をキャストできると思います..

$object = (object)array('name'=>'aviv');
echo $object->name; // prints aviv

そしてその逆..

$array= (array)$object;
echo $array['name']; // prints aviv
于 2010-02-22T17:50:22.710 に答える
0

たとえば、独自のクラスを実装できます

class PropertyTest {
 $month;
}

次に、コードの使用で

$object = new PropertyTest;
$object->month = "January";
echo $obejct->month;
于 2010-02-22T17:52:49.477 に答える