를 구현 & 바PHP 내가 foo는 즉 두 개의 클래스가 ArrayAccess
class bar extends foo
{
public $element = null;
public function __construct()
{
}
}
과 내가 원하는
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 매직 메소드에서 가져 왔습니다. 여기
, 난 가 안녕하세요은주의해야한다 고 말했다 방법과 같이주의해야한다 foo는의 __construct 기능과 의 sayHello에서 $ this-> elementId로부터에 전달해야을 saysomething되어하고 싶은 말 매개 변수 sayHello 함수는 __call 마법 메서드에서 렌더링됩니다. 내가 잘못 본게 아니라면
$a['saysomething']->sayHello('Hello Said!')->sayBye('Good Bye!');
놀랍도록 효과적입니다! 고맙습니다. @ 잭! – Guns
@ 총들 당신을 환영합니다; '$ bar [ 'sayomething']'은'bar' 객체가 아니라'foo' 객체를 반환한다는 점에 유의하십시오. 덕분에 –
!. 그러나 완벽하게 잘 작동하지만 체인 방법이 작동하지 않습니다. 나는'$ a [sayomething]] -> sayHello [ 'Hello Said!] -> sayBye ('안녕히 가세요! ');를 시도하고 있습니다. 어떻게 이것을 달성합니까? – Guns