我有两个类,即 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/