[英]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.