2014-02-17 5 views
3

를 구현 & 바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!'); 

답변

2

,이에 foo::offsetGet()을 변경해야합니다 :

public function offsetGet($offset) 
{ 
    if (!$this->offsetExists($offset)) { 
     return new self($this->elementId); 
    } else { 
     return $this->data[$offset]; 
    } 
} 

그것은 그 자체의 인스턴스를 반환하는 요소가 없다면 또한

같은 체인 방법 필요 주어진 오프셋에서. 말했다

, foo::__construct()null 이외의 값을 전달 bar::__construct()뿐만 아니라 에서 호출해야합니다 체인 호출에

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; 
} 
+0

놀랍도록 효과적입니다! 고맙습니다. @ 잭! – Guns

+1

@ 총들 당신을 환영합니다; '$ bar [ 'sayomething']'은'bar' 객체가 아니라'foo' 객체를 반환한다는 점에 유의하십시오. 덕분에 –

+0

!. 그러나 완벽하게 잘 작동하지만 체인 방법이 작동하지 않습니다. 나는'$ a [sayomething]] -> sayHello [ 'Hello Said!] -> sayBye ('안녕히 가세요! ');를 시도하고 있습니다. 어떻게 이것을 달성합니까? – Guns