首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现ArrayAccess

实现ArrayAccess
EN

Stack Overflow用户
提问于 2014-02-17 09:55:07
回答 1查看 454关注 0票数 3

我有两门课: foo & Bar

代码语言:javascript
复制
class bar extends foo
{

    public $element = null;

    public function __construct()
    {
    }
}

而foo类就像

代码语言:javascript
复制
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);
        }
    }
} 

当我运行下面的代码时,我要这样做:

代码语言:javascript
复制
$a = new bar();
$a['saysomething']->sayHello('Hello Said!');

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

这里,我想说的是,$this->elementId中应该从foo的__construct函数中传递, sayHello 应该作为方法,Hello表示应该作为sayHello函数的参数,而sayHello函数将由__call魔术方法E 216呈现。

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

代码语言:javascript
复制
$a['saysomething']->sayHello('Hello Said!')->sayBye('Good Bye!');
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-17 10:07:17

如果我没有弄错,您应该将foo::offsetGet()改为:

代码语言:javascript
复制
public function offsetGet($offset)
{
    if (!$this->offsetExists($offset)) {
        return new self($this->elementId);
    } else {
        return $this->data[$offset];
    }
}

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

也就是说,foo::__construct()也应该从bar::__construct()中调用,并且应该传递一个null以外的值。

代码语言:javascript
复制
class bar extends foo
{

    public $element = null;

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

更新

要链接调用,需要从__call()返回实例

代码语言:javascript
复制
public function __call($functionName, $arguments)
{
    if ($this->elementId !== null) {
        echo "Function $functionName called with arguments " . print_r($arguments, true);
    }
    return $this;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21825768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档