私はしばらくの間、 ArrayAccess
PHPの魔法(__get
、 )にだまされてきましたが、行き詰まっています。__set
配列であるいくつかのプロパティが読み取り専用であるクラスを実装しようとしています。これらはコンストラクターによって最初に設定されますが、その後は変更できません。
参照による魔法を使用__get
して、プロパティの任意の深さの配列要素にアクセスできます。これらのプロパティがを介してターゲットにされている場合は、例外をスローできると考えてい__set
ました。
ただし、問題は、配列要素の値にアクセスしているときに、PHPが__get
配列のその部分を参照によって返すように呼び出しているため、読み取りアクションか書き込みアクションかがわかりません。
(最悪の部分は、これが発生することを知っていましたがArrayAccess
、プロパティが実装されたオブジェクトのインスタンスであったことを考えると、可能な回避策としてだまされてきました)
簡単な例:
class Test{
public function &__get($key){
echo "[READ:{$key}]\n";
}
public function __set($key, $value){
echo "[WRITE:{$key}={$value}]\n";
}
}
$test = new Test;
$test->foo;
$test->foo = 'bar';
$test->foo['bar'];
$test->foo['bar'] = 'zip';
そして出力:
[READ:foo]
[WRITE:foo=bar]
[READ:foo]
[READ:foo] // here's the problem
現実的には、とにかくfoo
(私の例のように)値だけが必要ですが、それが読み取りではなく書き込みアクションであることを知る必要があります。
私はこれが達成できないことをすでに半分受け入れていますが、それでも私は希望を持っています。誰かが私が達成しようとしていることをどのように行うことができるかについて何か考えがありますか?
で考えられるいくつかの回避策を検討してArrayAccess
いましたが、私が知る限り、を呼び出すプロパティ表記を使用することを考えると、この場所に戻ることになります__get
。
更新: 。でもう1つの楽しい日ArrayAccess
。
(これは別の問題ですが、うまくいくと思います。キックのためだけに投稿します。)
class Mf_Params implements ArrayAccess{
private $_key = null;
private $_parent = null;
private $_data = array();
private $_temp = array();
public function __construct(Array $data = array(), $key = null, self $parent = null){
$this->_parent = $parent;
$this->_key = $key;
foreach($data as $key => $value){
$this->_data[$key] = is_array($value)
? new self($value, $key, $this)
: $value;
}
}
public function toArray(){
$array = array();
foreach($this->_data as $key => $value){
$array[$key] = $value instanceof self
? $value->toArray()
: $value;
}
return $array;
}
public function offsetGet($offset){
if(isset($this->_data[$offset])){
return $this->_data[$offset];
}
// if offset not exist return temp instance
return $this->_temp[$offset] = new self(array(), $offset, $this);
}
public function offsetSet($offset, $value){
$child = $this;
// copy temp instances to data after array reference chain
while(!is_null($parent = $child->_parent) && $parent->_temp[$child->_key] === $child){
$parent->_data[$child->_key] = $parent->_temp[$child->_key];
$child = $parent;
}
// drop temp
foreach($child->_temp as &$temp){
unset($temp);
}
if(is_null($offset)){
$this->_data[] = is_array($value)
? new self($value, null, $this)
: $value;
}else{
$this->_data[$offset] = is_array($value)
? new self($value, $offset, $this)
: $value;
}
}
public function offsetExists($offset){
return isset($this->_data[$offset]);
}
public function offsetUnset($offset){
unset($this->_data[$offset]);
}
}