PHP实现了ArrayAccess

时间:2014-02-17 09:55:08

标签: php magic-methods arrayaccess

我有两个课程viz foo&杆

class bar extends foo
{

    public $element = null;

    public function __construct()
    {
    }
}

并且Class foo为

class foo implements ArrayAccess
{

    private $data = [];
    private $elementId = null;

    public function __call($functionName, $arguments)
    {
        if ($this->elementId !== null) {
            echo "Function $functionName called with arguments " . print_r($arguments, true);
        }
        return true;
    }

    public function __construct($id = null)
    {
        $this->elementId = $id;
    }

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

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

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

    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset)) {
            $this->$offset = new foo($offset);
        }
    }
} 

当我运行下面的代码时,我想要那个:

$a = new bar();
$a['saysomething']->sayHello('Hello Said!');

应该从foo的__call魔术方法返回函数sayHello用参数Hello Said!调用。

在这里,我想说的是说些什么应该从foo的 __ construct 函数中传递 $ this-> elementId 并且 sayHello 应该被视为方法 Hello Said 应该作为参数用于sayHello函数,它将从呈现__call魔术法

另外,需要链接方法,如:

$a['saysomething']->sayHello('Hello Said!')->sayBye('Good Bye!');

1 个答案:

答案 0 :(得分:2)

如果我没弄错的话,你应该将foo::offsetGet()更改为:

public function offsetGet($offset)
{
    if (!$this->offsetExists($offset)) {
        return new self($this->elementId);
    } else {
        return $this->data[$offset];
    }
}

如果给定偏移处没有元素,则返回自身的实例。

也就是说,foo::__construct()应该从bar::__construct()调用并且传递的值不是null

class bar extends foo
{

    public $element = null;

    public function __construct()
    {
        parent::__construct(42);
    }
}

<强>更新

要进行链接调用,您需要从__call()

返回实例
public function __call($functionName, $arguments)
{
    if ($this->elementId !== null) {
        echo "Function $functionName called with arguments " . print_r($arguments, true);
    }
    return $this;
}
相关问题