2014-02-17 5 views
3

У меня есть два класса а именно Foo & BarPHP реализует ArrayAccess

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 Вызывается с аргументами Привет Сказал! из foo's __call magic method.

Здесь я хочу сказать saysomething должен быть принят в $ this-> elementId из __construct функции Foo и SayHello следует рассматривать как метод и Здравствуйте Упомянутая должны быть приняты как параметров для sayHello Функция, которая будет отображаться от __call magic method.

Кроме того, необходимо методы цепи, как:

$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() должен вызываться из bar::__construct(), а и передается значение, отличное null:

class bar extends foo 
{ 

    public $element = null; 

    public function __construct() 
    { 
     parent::__construct(42); 
    } 
} 

Update

Для цепи вызовов, необходимо вернуть экземпляр от __call():

public function __call($functionName, $arguments) 
{ 
    if ($this->elementId !== null) { 
     echo "Function $functionName called with arguments " . print_r($arguments, true); 
    } 
    return $this; 
} 
+0

удивительно эффективно! Спасибо тонну @ Jack! – Guns

+1

@Guns Добро пожаловать; что '$ bar ['saysomething']' не возвращает объект 'bar', а объект' foo'. –

+0

спасибо !. Это работает отлично, однако, когда я цепи методы это не работает. Я пытаюсь '$ a ['sayomething'] -> sayHello ['Hello Said!] -> sayBye (' Good Bye! ');'. Как мне это достичь? – Guns

Смежные вопросы