[英]PHP implements ArrayAccess
我有两个类viz 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函数传递$这个- > elementId和sayHello的应被视为方法和你好说的应该被视为针对这会从__call魔术方法来呈现sayHello的功能参数 。
此外,需要链接方法,如:
$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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.