PHP 实现 ArrayAccess

标签 php magic-methods arrayaccess

我有两个类,即 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!');

应该从 foo 的 __call 魔术方法返回 Function sayHello Called with arguments Hello Said!

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

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

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

最佳答案

如果我没记错的话,你应该把 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;
}

关于PHP 实现 ArrayAccess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21825768/

相关文章:

函数中的 PHP 异常 VS 返回用法(最佳实践)

php - 登录后根据mysql中的字段变量转到[location]

php - 为什么我的 __clone() 没有按预期工作?

php - 检查神奇设置的属性上是否存在属性

c++ - 为什么数组访问和指针算术不等同于完全优化?

php - 当用户状态变为1时如何进行更新查询

php - 如何使用 Zend Compressor Filter 压缩多个文件?

python:概括委托(delegate)方法

PHP 5.4 的简化字符串偏移读取

php - 数组访问、迭代器和 current()