PHP实现ArrayAccess
我有两门课,即foo和BarPHP实现ArrayAccess,php,magic-methods,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($fun
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的调用魔法方法
这里,,我想说的是,issaysomething应该从foo的\uu构造函数中传入$this->elementId,sayHello应该作为方法,并且Hello Said应该作为sayHello函数的参数,该函数将从\uu调用magic>中呈现方法
此外,还需要链接以下方法:
$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::u-construct()
也应该从bar::u-construct()
调用,并传递一个非null
的值:
class bar extends foo
{
public $element = null;
public function __construct()
{
parent::__construct(42);
}
}
public function __call($functionName, $arguments)
{
if ($this->elementId !== null) {
echo "Function $functionName called with arguments " . print_r($arguments, true);
}
return $this;
}
更新
要链接调用,需要从\u call()
返回实例:
非常有效!谢谢你,杰克@不客气;请注意,
$bar['saysomething']
不会返回bar
对象,而是返回foo
对象。谢谢!。但是,当我链接方法时,它就不起作用了。我正在尝试$a['saysomething']->说你好['Hello Said!]->说再见('再见!')代码>。如何实现这一点?@Guns在这种情况下,\u call()
必须返回$this
而不是返回true代码>。更新答案。太棒了!我希望我能给你15-20票!谢谢你,杰克