3

我有两个课程,即 foo 和 Bar

class bar extends foo
{

    public $element = null;

    public function __construct()
    {
    }
}

类 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!');

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

在这里,我想说的是saysomething应该从 foo 的__construct函数传入$this->elementId ,并且sayHello应该作为方法Hello Said应该作为sayHello 函数的参数,该函数将从__call 魔术方法呈现。

此外,需要链接方法,例如:

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

1 回答 1

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;
}
于 2014-02-17T10:07:17.530 回答