无容器数组的ArrayAccess的实现迭代器接口

问题描述 投票:0回答:1

这是我为ArrayAccess实现https://www.php.net/manual/en/class.iterator.php的尝试。许多示例都将容器数组用作私有成员变量。但如果可能,我不想使用容器数组。我不希望使用容器数组的主要原因是因为我想在具有智能感知等情况下都像这样$DomainData->domainId来访问属性(数组键)。

演示:https://ideone.com/KLPwwY

class DomainData implements ArrayAccess, Iterator
{
    private $position = 0;
    public $domainId;
    public $color;

    public function __construct($data = array())
    {
        $this->position = 0;
        foreach ($data as $key => $value) {
            $this[$key] = $value;
        }
    }

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

    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }

    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    public function offsetUnset($offset)
    {
        $this->$offset = null;
    }

    /*****************************************************************/
    /*                     Iterator Implementation                   */
    /*****************************************************************/

    public function rewind()
    {
        $this->position = 0;
    }

    public function current()
    {
        return $this[$this->position];
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function valid()
    {
        return isset($this[$this->position]);
    }
}

调用:

$domainData = new DomainData([
    "domainId" => 1,
    "color" => "red"
]);

var_dump($domainData);

foreach($domainData as $k => $v){
    var_dump("domainData[$k] = $v");
}

实际:

object(DomainData)#1 (3) {
  ["position":"DomainData":private]=>
  int(0)
  ["domainId"]=>
  int(1)
  ["color"]=>
  string(3) "red"
}

期望:

object(DomainData)#1 (3) {
  ["position":"DomainData":private]=>
  int(0)
  ["domainId"]=>
  int(1)
  ["color"]=>
  string(3) "red"
}
string(24) "domainData[domainId] = 1"
string(23) "domainData[color] = red"

这是我为ArrayAccess实现https://www.php.net/manual/zh/class.iterator.php的尝试。许多示例都将容器数组用作私有成员变量。但我不想使用...

php arrays iterator php-5.6 arrayaccess
1个回答
0
投票

请尝试get_object_vars() php函数以根据作用域获取给定对象的可访问非静态属性。

© www.soinside.com 2019 - 2024. All rights reserved.