我有两门课: 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!来自foo的__call魔术方法。
这里,我想说的是,$this->elementId中应该从foo的__construct函数中传递, sayHello 应该作为方法,Hello表示应该作为sayHello函数的参数,而sayHello函数将由__call魔术方法E 216呈现。
此外,还需要链接方法,例如:
$a['saysomething']->sayHello('Hello Said!')->sayBye('Good Bye!');发布于 2014-02-17 10:07:17
如果我没有弄错,您应该将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;
}https://stackoverflow.com/questions/21825768
复制相似问题