4

次のようなクラスの例では、次のようになります。

class Test{
    public function &__get($name){
        print_r($name);
    }
}

のインスタンスは、次のTestように出力をキックバックします。

$myTest = new Test;
$myTest->foo['bar']['hello'] = 'world';
//outputs only foo

barの要素fooとのhello要素barがターゲットになっていることを(前の例から)示して、アクセスされている配列の次元に関する詳細情報を取得する方法はありますか?

4

3 に答える 3

3

現在の実装ではできません。これを機能させるには、配列オブジェクト(つまり、を実装するオブジェクトArrayAccess)を作成する必要があります。何かのようなもの:

class SuperArray implements ArrayAccess {
    protected $_data = array();
    protected $_parents = array();

    public function __construct(array $data, array $parents = array()) {
        $this->_parents = $parents;
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $value = new SuperArray($value, array_merge($this->_parents, array($key)));
            }
            $this[$key] = $value;
        }
    }

    public function offsetGet($offset) {
        if (!empty($this->_parents)) echo "['".implode("']['", $this->_parents)."']";
        echo "['$offset'] is being accessed\n";
        return $this->_data[$offset];
    } 

    public function offsetSet($offset, $value) {
        if ($offset === '') $this->_data[] = $value;
        else $this->_data[$offset] = $value;
    } 

    public function offsetUnset($offset) {
        unset($this->_data[$offset]);
    } 

    public function offsetExists($offset) {
        return isset($this->_data[$offset]);
    } 
}

class Test{
    protected $foo;

    public function __construct() {
        $array['bar']['hello'] = 'world';
        $this->foo = new SuperArray($array); 
    }

    public function __get($name){
        echo $name.' is being accessed.'.PHP_EOL;
        return $this->$name;
    }
}

$test = new Test;
echo $test->foo['bar']['hello'];

出力する必要があります:

foo is being accessed.
['bar'] is being accessed
['bar']['hello'] is being accessed
world
于 2010-12-24T16:30:05.057 に答える
1

いいえ、できません。 $myTest->foo['bar']['hello'] = 'world';次の翻訳を経て、 $myTest->__get('foo')['bar']['hello'] = 'world';それらを部分的に分割します

$tmp = $myTest->__get('foo')
$tmp['bar']['hello'] = 'world';

できることは、ArrayAccess派生オブジェクトを作成することです。あなたがあなた自身を定義し、offsetSet()それをから返すところ__get()

于 2010-12-24T16:15:23.270 に答える
1

配列を返す代わりに、 ArrayAccessを実装するオブジェクトを返すことができます。オブジェクトは常に返され、参照によって渡されます。これにより、少なくともレベルが下がる問題が発生します。

于 2010-12-24T16:18:16.593 に答える