るPHPのインターフェースにより物体の特性にアクセスと配列表記?
-
22-09-2019 - |
質問
るPHP SPLインターフェースによりオブジェクトいます:
$object->month = 'january';
echo $object['month']; // january
$record['day'] = 'saturday';
echo $record->day; // saturday
例えばなどの図書館のような主義Doctrine_Record)
方法を実施。たって使用ArrayObjectもあるんですが、その振る舞いをしまうと思った.
すなわち
$object = new ArrayObject();
$object['a'] = 'test';
$object['a'] == $object->a; // false
編集:
いろいろとbarebone実施を呼んだとき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のの
ソースコードのためのDoctrine_Record のを参照してください。 P>
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
のDocblockから
<時間>教義サブクラス
のためのアレイアクセスおよびプロパティオーバーロードインターフェースを提供
メソッド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マニュアルにある
他のヒント
あなたがここに二つの異なるものを使用しています:
$a[key]
ためArrayAccessインターフェイスと
http://php.net/manual/en/language.oop5.overloading。 PHP の$a->key
のための
何が起こるか。
$a[key]
(ArrayAccessのから継承)$a->offsetGet(key)
と$a->key
を呼び出します($a->__get(key)
のようなコンテキストで)$a->__set(key, val)
または$a->key = val
を呼び出します。
私はあなたがオブジェクトと配列をキャストすることができると思います..
$object = (object)array('name'=>'aviv');
echo $object->name; // prints aviv
そしてその逆..
$array= (array)$object;
echo $array['name']; // prints aviv
あなたは、独自のクラスを実装することができます 例えば
class PropertyTest {
$month;
}
次に、コード使用中の
$object = new PropertyTest;
$object->month = "January";
echo $obejct->month;
私は質問に答えご利用のコード例は、たとえ小さな追加しました。
<?php
$object = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS);
$object['a'] = 'test';
var_dump($object['a'] == $object->a); // expected: bool(true)
$object->month = 'january';
echo $object['month']; // expected: january
$object['day'] = 'saturday';
echo $object->day; // expected: saturday
ArrayObject
受け入れ、2回のコンストラクタ引数はどうしたらよいですか
ArrayObject::STD_PROP_LIST オブジェクトのプロパティをおいてその正常に機能がアクセスリスト(var_dump,foreachます。
ArrayObject::ARRAY_AS_PROPS 応募が可能と特性(読み込みおよび書き込み).